lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
cc0-1.0
a520f07e04b12a4bba9ec04d91fc389637270537
0
iterami/common,iterami/common,iterami/common
'use strict'; // Required args: base // Optional args: entity, offset-x, offset-y, offset-z function webgl_attach(args){ args = core_args({ 'args': args, 'defaults': { 'entity': '_webgl-camera', 'offset-x': 0, 'offset-y': 0, 'offset-z': 0, }, }); core_entities[args['entity']]['attach'] = { 'offset': { 'x': args['offset-x'], 'y': args['offset-y'], 'z': args['offset-z'], }, 'to': args['base'], }; } // Required args: entity // Optional args: axes function webgl_billboard(args){ args = core_args({ 'args': args, 'defaults': { 'axes': { 'y': 'y', }, }, }); for(var axis in args['axes']){ core_entities[args['entity']]['rotate'][axis] = 360 - core_entities['_webgl-camera']['rotate'][args['axes'][axis]]; } } // Required args: colorData, indexData, normalData, textureData, vertexData function webgl_buffer_set(args){ return { 'color': webgl_buffer_set_type({ 'data': args['colorData'], }), /* 'index': webgl_buffer_set_type({ 'data': args['indexData'], 'type': 'Uint16Array', }), */ 'normal': webgl_buffer_set_type({ 'data': args['normalData'], }), 'texture': webgl_buffer_set_type({ 'data': args['textureData'], }), 'vertex': webgl_buffer_set_type({ 'data': args['vertexData'], }), }; } // Required args: data // Optional args: type function webgl_buffer_set_type(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'Float32Array', }, }); var buffer = webgl_buffer.createBuffer(); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, buffer ); webgl_buffer.bufferData( webgl_buffer.ARRAY_BUFFER, new window[args['type']](args['data']), webgl_buffer.STATIC_DRAW ); return buffer; } function webgl_camera_first(){ if(core_mouse['pointerlock-state']){ webgl_camera_rotate({ 'x': core_mouse['movement-y'] / 10, 'y': core_mouse['movement-x'] / 10, }); } } // Optional args: speed, strafe, y function webgl_camera_move(args){ args = core_args({ 'args': args, 'defaults': { 'speed': 1, 'strafe': false, 'y': 0, }, }); var movement = math_move_3d({ 'angle': core_entities['_webgl-camera']['rotate']['y'], 'speed': args['speed'], 'strafe': args['strafe'], }); core_entities['_webgl-camera']['dx'] += movement['x']; core_entities['_webgl-camera']['dy'] += args['y']; core_entities['_webgl-camera']['dz'] += movement['z']; } // Optional args: x, xlock, y, z function webgl_camera_rotate(args){ args = core_args({ 'args': args, 'defaults': { 'x': 0, 'xlock': args['xlock'] !== false, 'y': 0, 'z': 0, }, }); var axes = { 'x': args['x'], 'y': args['y'], 'z': args['z'], }; for(var axis in axes){ core_entities['_webgl-camera']['rotate'][axis] = math_clamp({ 'max': 360, 'min': 0, 'value': math_round({ 'number': core_entities['_webgl-camera']['rotate'][axis] + axes[axis], }), 'wrap': true, }); } if(args['xlock']){ var max = 89; if(core_entities['_webgl-camera']['rotate']['x'] > 180){ max += 271; } core_entities['_webgl-camera']['rotate']['x'] = math_clamp({ 'max': max, 'min': max - 89, 'value': core_entities['_webgl-camera']['rotate']['x'], }); } for(var axis in axes){ core_entities['_webgl-camera']['rotate-radians'][axis] = math_degrees_to_radians({ 'degrees': core_entities['_webgl-camera']['rotate'][axis], }); } } // Required args: color function webgl_clearcolor_set(args){ webgl_properties['clearcolor'] = args['color']; webgl_buffer.clearColor( webgl_properties['clearcolor']['red'], webgl_properties['clearcolor']['green'], webgl_properties['clearcolor']['blue'], webgl_properties['clearcolor']['alpha'] ); } function webgl_draw(){ webgl_buffer.viewport( 0, 0, webgl_buffer.viewportWidth, webgl_buffer.viewportHeight ); webgl_buffer.clear(webgl_buffer.COLOR_BUFFER_BIT | webgl_buffer.DEPTH_BUFFER_BIT); math_matrix_identity({ 'id': 'camera', }); math_matrix_rotate({ 'dimensions': [ core_entities['_webgl-camera']['rotate-radians']['x'], core_entities['_webgl-camera']['rotate-radians']['y'], core_entities['_webgl-camera']['rotate-radians']['z'], ], 'id': 'camera', }); math_matrix_translate({ 'dimensions': [ core_entities['_webgl-camera']['position']['x'], core_entities['_webgl-camera']['position']['y'], core_entities['_webgl-camera']['position']['z'], ], 'id': 'camera', }); webgl_buffer.disable(webgl_buffer.DEPTH_TEST); core_group_modify({ 'groups': [ 'depthfalse', ], 'todo': function(entity){ webgl_draw_entity(entity); }, }); webgl_buffer.enable(webgl_buffer.DEPTH_TEST); core_group_modify({ 'groups': [ 'depthtrue', ], 'todo': function(entity){ if(core_entities[entity]['alpha'] === 1){ webgl_draw_entity(entity); } }, }); core_group_modify({ 'groups': [ 'depthtrue', ], 'todo': function(entity){ if(core_entities[entity]['alpha'] < 1){ webgl_draw_entity(entity); } }, }); webgl_canvas.clearRect( 0, 0, webgl_canvas_properties['width'], webgl_canvas_properties['height'] ); webgl_canvas.drawImage( document.getElementById('buffer'), 0, 0 ); for(var text in webgl_text){ Object.assign( webgl_canvas, webgl_text[text]['properties'] ); webgl_canvas.fillText( webgl_text[text]['text'], webgl_text[text]['x'], webgl_text[text]['y'] ); } if(webgl_properties['pointer'] !== false){ webgl_canvas.fillStyle = webgl_properties['pointer']; webgl_canvas.fillRect( webgl_canvas_properties['width-half'] - 1, webgl_canvas_properties['height-half'] - 1, 2, 2 ); } } function webgl_drawloop(){ if(!core_menu_open){ webgl_draw(); } webgl_animationFrame = window.requestAnimationFrame(webgl_drawloop); } function webgl_draw_entity(entity){ if(core_entities[entity]['draw'] === false){ return; } if(core_entities[entity]['billboard'] === true){ webgl_billboard({ 'entity': entity, }); } math_matrix_clone({ 'id': 'camera', 'to': 'cache', }); math_matrix_translate({ 'dimensions': [ -core_entities[entity]['position']['x'], -core_entities[entity]['position']['y'], -core_entities[entity]['position']['z'], ], 'id': 'camera', }); math_matrix_rotate({ 'dimensions': [ core_entities[entity]['rotate-radians']['x'], core_entities[entity]['rotate-radians']['y'], core_entities[entity]['rotate-radians']['z'], ], 'id': 'camera', }); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['normal'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexNormal'], 3, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['color'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexColor'], 4, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['vertex'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexPosition'], 3, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['texture'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_texturePosition'], 2, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.activeTexture(webgl_buffer.TEXTURE0); webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, core_entities[entity]['texture'] ); webgl_buffer.uniform1i( webgl_uniformlocations['sampler'], 0 ); /* webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['index'] ); */ webgl_buffer.uniform1f( webgl_uniformlocations['alpha'], core_entities[entity]['alpha'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_normalMatrix'], 0, math_matrices['perspective'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_perspectiveMatrix'], 0, math_matrices['perspective'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_cameraMatrix'], 0, math_matrices['camera'] ); webgl_buffer.drawArrays( webgl_buffer[core_entities[entity]['mode']], 0, core_entities[entity]['vertices-length'] ); math_matrix_copy({ 'id': 'cache', 'to': 'camera', }); } // Optional args: ambient-blue, ambient-green, ambient-red, camera, clear-alpha, clear-blue, clear-green, clear_red, cleardepth, contextmenu, fog, grabity-acceleration, gravity-max, speed function webgl_init(args){ args = core_args({ 'args': args, 'defaults': { 'ambient-blue': 1, 'ambient-green': 1, 'ambient-red': 1, 'camera': 'free', 'clear-alpha': 1, 'clear-blue': 0, 'clear-green': 0, 'clear-red': 0, 'cleardepth': 1, 'contextmenu': true, 'direction-blue': 1, 'direction-green': 1, 'direction-red': 1, 'direction-vector': false, 'fog': -0.0001, 'gravity-acceleration': -0.05, 'gravity-max': -1, 'speed': .1, }, }); webgl_canvas_properties = { 'fillStyle': '#fff', 'font': webgl_fonts['medium'], 'height': 0, 'height-half': 0, 'lineJoin': 'miter', 'lineWidth': 1, 'strokeStyle': '#fff', 'textAlign': 'start', 'textBaseline': 'alphabetic', 'width': 0, 'width-half': 0, }; webgl_properties = { 'ambientlighting': { 'blue': args['ambient-blue'], 'green': args['ambient-green'], 'red': args['ambient-red'], }, 'camera': { 'speed': args['speed'], 'type': args['camera'], }, 'clearcolor': { 'alpha': args['clear-alpha'], 'blue': args['clear-blue'], 'green': args['clear-green'], 'red': args['clear-red'], }, 'cleardepth': args['cleardepth'], 'collision-range': 2.5, 'directionlighting': { 'blue': args['direction-blue'], 'green': args['direction-green'], 'red': args['direction-red'], 'vector': args['direction-vector'], }, 'fog': args['fog'], 'gravity': { 'acceleration': args['gravity-acceleration'], 'max': args['gravity-max'], }, 'pointer': false, }; var properties = ''; if(!args['contextmenu']){ properties = ' oncontextmenu="return false" '; } core_html({ 'parent': document.body, 'properties': { 'id': 'wrap', 'innerHTML': '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>', }, }); math_matrices['camera'] = math_matrix_create(); math_matrices['perspective'] = math_matrix_create(); webgl_buffer = document.getElementById('buffer').getContext( 'webgl', { 'alpha': false, 'antialias': true, 'depth': true, 'premultipliedAlpha': false, 'preserveDrawingBuffer': false, 'stencil': false, } ); webgl_canvas = document.getElementById('canvas').getContext('2d'); window.onresize = webgl_resize; webgl_resize(); webgl_clearcolor_set({ 'color': { 'alpha': webgl_properties['clearcolor']['alpha'], 'blue': webgl_properties['clearcolor']['blue'], 'green': webgl_properties['clearcolor']['green'], 'red': webgl_properties['clearcolor']['red'], }, }); webgl_buffer.clearDepth(webgl_properties['cleardepth']); webgl_buffer.enable(webgl_buffer.CULL_FACE); webgl_buffer.enable(webgl_buffer.DEPTH_TEST); webgl_shader_update(); webgl_buffer.blendFunc( webgl_buffer.SRC_ALPHA, webgl_buffer.ONE_MINUS_SRC_ALPHA ); webgl_buffer.enable(webgl_buffer.BLEND); core_entity_set({ 'default': true, 'groups': [ 'depthtrue', ], 'properties': { 'alpha': 1, 'attach': false, 'billboard': false, 'collides': false, 'collision': false, 'color': [], 'draw': true, 'dx': 0, 'dy': 0, 'dz': 0, 'gravity': false, /* 'index': [ 0, 1, 2, 0, 2, 3, ], */ 'mode': 'TRIANGLE_FAN', 'normals': [], 'position': { 'x': 0, 'y': 0, 'z': 0, }, 'rotate': { 'x': 0, 'y': 0, 'z': 0, }, 'rotate-radians': { 'x': 0, 'y': 0, 'z': 0, }, 'scale': { 'x': 1, 'y': 1, 'z': 1, }, 'textureData': [ 0, 1, 0, 0, 1, 0, 1, 1, ], 'vertices-length': 0, }, 'todo': function(entity){ core_entities[entity]['normals'] = webgl_normals({ 'x-rotation': core_entities[entity]['rotate']['x'], 'y-rotation': core_entities[entity]['rotate']['y'], 'z-rotation': core_entities[entity]['rotate']['z'], }); if(core_entities[entity]['draw'] === false){ return; } core_entities[entity]['rotate-radians'] = { 'x': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['x'], }), 'y': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['y'], }), 'z': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['z'], }), }; core_entities[entity]['vertices-length'] = core_entities[entity]['vertices'].length / 3; core_entities[entity]['buffer'] = webgl_buffer_set({ 'colorData': core_entities[entity]['color'], //'indexData': core_entities[entity]['index'], 'normalData': core_entities[entity]['normals'], 'textureData': core_entities[entity]['textureData'], 'vertexData': core_entities[entity]['vertices'], }); webgl_texture_set({ 'entityid': entity, 'image': webgl_textures['_default'], }); }, 'type': 'webgl', }); core_entity_create({ 'id': '_webgl-camera', 'properties': { 'collides': true, 'draw': false, 'gravity': webgl_properties['camera']['type'] === 'gravity', }, }); core_interval_modify({ 'id': 'webgl-interval', 'interval': core_storage_data['frame-ms'], 'paused': true, 'todo': webgl_logicloop, }); if(!core_menu_open){ webgl_setmode(); } } function webgl_logicloop(){ core_entities['_webgl-camera']['dx'] = 0; core_entities['_webgl-camera']['dz'] = 0; if(!core_entities['_webgl-camera']['gravity']){ core_entities['_webgl-camera']['dy'] = 0; } if(webgl_properties['camera']['type'] !== false){ if(core_keys[65]['state']){ webgl_camera_move({ 'speed': -webgl_properties['camera']['speed'], 'strafe': true, }); } if(core_keys[68]['state']){ webgl_camera_move({ 'speed': webgl_properties['camera']['speed'], 'strafe': true, }); } if(core_keys[83]['state']){ webgl_camera_move({ 'speed': webgl_properties['camera']['speed'], }); } if(core_keys[87]['state']){ webgl_camera_move({ 'speed': -webgl_properties['camera']['speed'], }); } if(webgl_properties['camera']['type'] === 'free'){ if(core_keys[32]['state']){ webgl_camera_move({ 'speed': 0, 'y': webgl_properties['camera']['speed'], }); } if(core_keys[67]['state']){ webgl_camera_move({ 'speed': 0, 'y': -webgl_properties['camera']['speed'], }); } } } logic(); core_group_modify({ 'groups': [ 'webgl', ], 'todo': function(entity){ webgl_logicloop_handle_entity(entity); }, }); } function webgl_logicloop_handle_entity(entity){ if(core_entities[entity]['logic']){ core_entities[entity]['logic'](); } core_entities[entity]['rotate-radians'] = { 'x': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['x'], }), 'y': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['y'], }), 'z': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['z'], }), }; if(core_entities[entity]['gravity']){ core_entities[entity]['dy'] = Math.max( core_entities[entity]['dy'] + webgl_properties['gravity']['acceleration'], webgl_properties['gravity']['max'] ); } if(core_entities[entity]['collides']){ for(var other_entity in core_entities){ if(entity !== other_entity && core_entities[other_entity]['collision']){ webgl_normals_collision({ 'entity0id': entity, 'entity1id': other_entity, }); } } } if(core_entities[entity]['attach'] !== false){ var attachto = core_entities[core_entities[entity]['attach']['to']]; for(var axis in core_entities[entity]['position']){ core_entities[entity]['position'][axis] = attachto['position'][axis] + core_entities[entity]['attach']['offset'][axis]; } }else{ for(var axis in core_entities[entity]['position']){ core_entities[entity]['position'][axis] += core_entities[entity]['d' + axis]; } } } // Optional args: x-rotation, y-rotation, z-rotation function webgl_normals(args){ args = core_args({ 'args': args, 'defaults': { 'x-rotation': 0, 'y-rotation': 0, 'z-rotation': 0, }, }); var normal_x = 0; var normal_y = 0; var normal_z = 0; if(args['x-rotation'] !== 0){ normal_z = math_round({ 'number': Math.sin(math_degrees_to_radians({ 'degrees': args['x-rotation'], })), }); }else if(args['z-rotation'] !== 0){ normal_x = -math_round({ 'number': Math.sin(math_degrees_to_radians({ 'degrees': args['z-rotation'], })), }); }else{ normal_y = math_round({ 'number': Math.cos(math_degrees_to_radians({ 'degrees': args['y-rotation'], })), }); } return [ normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, ]; } // Required args: entity0id, entity1id function webgl_normals_collision(args){ var entity0 = core_entities[args['entity0id']]; var entity1 = core_entities[args['entity1id']]; if(entity1['normals'][0] !== 0){ if(entity1['normals'][0] === 1 && entity0['dx'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] && entity0['position']['x'] <= entity1['position']['x'] + webgl_properties['collision-range'] && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] + 1 && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range'] - 1){ entity0['dx'] = 0; entity0['position']['x'] = entity1['position']['x'] + webgl_properties['collision-range']; } }else if(entity1['normals'][0] === -1 && entity0['dx'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] + 1 && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range'] - 1){ entity0['dx'] = 0; entity0['position']['x'] = entity1['position']['x'] - webgl_properties['collision-range']; } } } if(entity1['normals'][1] !== 0){ if(entity1['normals'][1] === 1 && entity0['dy'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['y'] >= entity1['position']['y'] && entity0['position']['y'] <= entity1['position']['y'] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range']){ entity0['dy'] = 0; entity0['position']['y'] = entity1['position']['y'] + webgl_properties['collision-range']; } }else if(entity1['normals'][1] === -1 && entity0['dy'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['y'] >= entity1['position']['y'] - webgl_properties['collision-range'] && entity0['position']['y'] <= entity1['position']['y'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range']){ entity0['dy'] = 0; entity0['position']['y'] = entity1['position']['y'] - webgl_properties['collision-range']; } } } if(entity1['normals'][2] !== 0){ if(entity1['normals'][2] === 1 && entity0['dz'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] + 1 && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] - 1 && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][8] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] && entity0['position']['z'] <= entity1['position']['z'] + webgl_properties['collision-range']){ entity0['dz'] = 0; entity0['position']['z'] = entity1['position']['z'] + webgl_properties['collision-range']; } }else if(entity1['normals'][2] === -1 && entity0['dz'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] + 1 && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] - 1 && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][8] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z']){ entity0['dz'] = 0; entity0['position']['z'] = entity1['position']['z'] - webgl_properties['collision-range']; } } } } function webgl_perspective(){ math_matrices['perspective'][0] = webgl_canvas_properties['height'] / webgl_canvas_properties['width']; math_matrices['perspective'][5] = 1; math_matrices['perspective'][10] = -1; math_matrices['perspective'][11] = -1; math_matrices['perspective'][14] = -2; } // Required args: id, shaderlist function webgl_program_create(args){ var program = webgl_buffer.createProgram(); for(var shader in args['shaderlist']){ webgl_buffer.attachShader( program, args['shaderlist'][shader] ); } webgl_buffer.linkProgram(program); webgl_buffer.useProgram(program); return program; } function webgl_resize(){ var buffer = document.getElementById('buffer'); var canvas = document.getElementById('canvas'); webgl_canvas_properties['height'] = window.innerHeight; webgl_canvas_properties['height-half'] = webgl_canvas_properties['height'] / 2; buffer.height = webgl_canvas_properties['height']; canvas.height = webgl_canvas_properties['height']; webgl_canvas_properties['width'] = window.innerWidth; webgl_canvas_properties['width-half'] = webgl_canvas_properties['width'] / 2; buffer.width = webgl_canvas_properties['width']; canvas.width = webgl_canvas_properties['width']; webgl_buffer.viewportHeight = webgl_canvas_properties['height']; webgl_buffer.viewportWidth = webgl_canvas_properties['width']; webgl_buffer.viewport(0, 0, webgl_canvas_properties['height'], webgl_canvas_properties['width']); Object.assign( webgl_buffer, webgl_canvas_properties ); webgl_perspective(); core_call({ 'todo': 'resize_logic', }); } // Optional args: mode, newgame function webgl_setmode(args){ args = core_args({ 'args': args, 'defaults': { 'mode': 0, 'newgame': false, }, }); window.cancelAnimationFrame(webgl_animationFrame); core_storage_save(); core_entity_remove_all(); webgl_resize(); core_entities['_webgl-camera']['position'] = { 'x': 0, 'y': 0, 'z': 0, }; core_entities['_webgl-camera']['rotate'] = { 'x': 0, 'y': 0, 'z': 0, }; core_mode = args['mode']; core_call({ 'args': core_mode, 'todo': 'load_data', }); if(args['newgame']){ core_escape(); } webgl_animationFrame = window.requestAnimationFrame(webgl_drawloop); core_interval_resume_all(); } // Required args: properties function webgl_setcanvasproperties(args){ Object.assign( webgl_canvas_properties, args['properties'] ); Object.assign( webgl_buffer, args['properties'] ); } // Required args: id, source, type function webgl_shader_create(args){ var shader = webgl_buffer.createShader(args['type']); webgl_buffer.shaderSource( shader, args['source'] ); webgl_buffer.compileShader(shader); return shader; } function webgl_shader_update(){ var fogstring = webgl_properties['fog'] !== false ? ('mix(' + 'vec4(' + webgl_properties['clearcolor']['red'] + ',' + webgl_properties['clearcolor']['green'] + ',' + webgl_properties['clearcolor']['blue'] + ',' + webgl_properties['clearcolor']['alpha'] + '),' + 'vec_fragmentColor,' + 'clamp(exp(' + webgl_properties['fog'] + ' * float_fogDistance * float_fogDistance), 0.0, 1.0)' + ')') : 'vec_fragmentColor'; var fragment_shader = webgl_shader_create({ 'id': 'fragment', 'source': 'precision mediump float;' + 'uniform float alpha;' + 'uniform sampler2D sampler;' + 'varying float float_fogDistance;' + 'varying vec2 vec_textureCoord;' + 'varying vec3 vec_lighting;' + 'varying vec4 vec_fragmentColor;' + 'void main(void){' + 'gl_FragColor = ' + fogstring + ' * texture2D(sampler, vec_textureCoord) * vec4(vec_lighting, 1.0) * alpha;' + '}', 'type': webgl_buffer.FRAGMENT_SHADER, }); var directionstring = webgl_properties['directionlighting']['vector'] !== false ? (' + (vec3(' + webgl_properties['directionlighting']['red'] + ',' + webgl_properties['directionlighting']['green'] + ',' + webgl_properties['directionlighting']['blue'] + ') * max(dot(transformedNormal.xyz, normalize(vec3(' + webgl_properties['directionlighting']['vector'] + '))),0.0));') : ''; var vertex_shader = webgl_shader_create({ 'id': 'vertex', 'source': 'attribute vec2 vec_texturePosition;' + 'attribute vec3 vec_vertexNormal;' + 'attribute vec4 vec_vertexColor;' + 'attribute vec4 vec_vertexPosition;' + 'uniform mat4 mat_cameraMatrix;' + 'uniform mat4 mat_normalMatrix;' + 'uniform mat4 mat_perspectiveMatrix;' + 'varying float float_fogDistance;' + 'varying vec2 vec_textureCoord;' + 'varying vec3 vec_lighting;' + 'varying vec4 vec_fragmentColor;' + 'void main(void){' + 'gl_Position = mat_perspectiveMatrix * mat_cameraMatrix * vec_vertexPosition;' + 'float_fogDistance = length(gl_Position.xyz);' + 'vec_fragmentColor = vec_vertexColor;' + 'vec_textureCoord = vec_texturePosition;' + 'vec4 transformedNormal = mat_normalMatrix * vec4(vec_vertexNormal, 1.0);' + 'vec_lighting = vec3(' + webgl_properties['ambientlighting']['red'] + ',' + webgl_properties['ambientlighting']['green'] + ',' + webgl_properties['ambientlighting']['blue'] + ')' + directionstring + ';' + '}', 'type': webgl_buffer.VERTEX_SHADER, }); var program = webgl_program_create({ 'id': 'shaders', 'shaderlist': [ fragment_shader, vertex_shader, ], }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexColor', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexNormal', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexPosition', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_texturePosition', 'program': program, }); webgl_uniformlocations = { 'alpha': webgl_buffer.getUniformLocation( program, 'alpha' ), 'mat_cameraMatrix': webgl_buffer.getUniformLocation( program, 'mat_cameraMatrix' ), 'mat_normalMatrix': webgl_buffer.getUniformLocation( program, 'mat_normalMatrix' ), 'mat_perspectiveMatrix': webgl_buffer.getUniformLocation( program, 'mat_perspectiveMatrix' ), 'sampler': webgl_buffer.getUniformLocation( program, 'sampler' ), }; webgl_buffer.deleteProgram(program); } // Optional args: color function webgl_skybox(args){ args = core_args({ 'args': args, 'defaults': { 'color': webgl_vertexcolorarray(), }, }); core_entity_create({ 'id': 'skybox-back', 'properties': { 'color': args['color'], 'rotate': { 'x': 270, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-back', 'offset-z': 5, }); core_entity_create({ 'id': 'skybox-front', 'properties': { 'color': args['color'], 'rotate': { 'x': 90, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-front', 'offset-z': -5, }); core_entity_create({ 'id': 'skybox-left', 'properties': { 'color': args['color'], 'rotate': { 'z': 270, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-left', 'offset-x': -5, }); core_entity_create({ 'id': 'skybox-right', 'properties': { 'color': args['color'], 'rotate': { 'z': 90, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-right', 'offset-x': 5, }); core_entity_create({ 'id': 'skybox-top', 'properties': { 'color': args['color'], 'rotate': { 'x': 180, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-top', 'offset-y': 5, }); core_group_move({ 'entities': [ 'skybox-back', 'skybox-front', 'skybox-left', 'skybox-right', 'skybox-top', ], 'from': 'depthtrue', 'to': 'depthfalse', }); } // Required args: entityid // Optional args: image function webgl_texture_set(args){ args = core_args({ 'args': args, 'defaults': { 'image': webgl_textures['_default'], }, }); core_entities[args['entityid']]['texture'] = webgl_buffer.createTexture(); core_entities[args['entityid']]['image'] = core_image({ 'id': args['entityid'] + '-texture', 'src': args['image'], 'todo': function(){ webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, core_entities[args['entityid']]['texture'] ); webgl_buffer.texImage2D( webgl_buffer.TEXTURE_2D, 0, webgl_buffer.RGBA, webgl_buffer.RGBA, webgl_buffer.UNSIGNED_BYTE, core_entities[args['entityid']]['image'] ); webgl_buffer.texParameteri( webgl_buffer.TEXTURE_2D, webgl_buffer.TEXTURE_MAG_FILTER, webgl_buffer.NEAREST ); webgl_buffer.texParameteri( webgl_buffer.TEXTURE_2D, webgl_buffer.TEXTURE_MIN_FILTER, webgl_buffer.NEAREST ); webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, void 0 ); }, }); } // Optional args: id, quality, type function webgl_uri(args){ args = core_args({ 'args': args, 'defaults': { 'id': 'buffer', 'quality': 1, 'type': 'image/png', }, }); return document.getElementById(args['id']).toDataURL( args['type'], args['quality'] ); } // Required args: attribute, program function webgl_vertexattribarray_set(args){ webgl_attributes[args['attribute']] = webgl_buffer.getAttribLocation( args['program'], args['attribute'] ); webgl_buffer.enableVertexAttribArray(webgl_attributes[args['attribute']]); } // Optional args: rgbarray, vertexcount function webgl_vertexcolorarray(args){ args = core_args({ 'args': args, 'defaults': { 'rgbarray': [ core_random_rgb(), core_random_rgb(), core_random_rgb(), core_random_rgb(), ], 'vertexcount': 4, }, }); while(args['rgbarray'].length < args['vertexcount']){ args['rgbarray'].push(args['rgbarray'][0]); } var color = []; for(var i = 0; i < args['vertexcount']; i++){ color.push( args['rgbarray'][i]['red'] / 256, args['rgbarray'][i]['green'] / 256, args['rgbarray'][i]['blue'] / 256, 1, ); } return color; } var webgl_animationFrame = 0; var webgl_attributes = {}; var webgl_buffer = 0; var webgl_canvas = 0; var webgl_fonts = { 'big': '300% monospace', 'medium': '200% monospace', 'small': '100% monospace', }; var webgl_canvas_properties = {}; var webgl_properties = {}; var webgl_text = {}; var webgl_textures = { '_debug': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAD1BMVEUAAP8A/wD/AAAAAAD///8hKtLYAAAAIklEQVQoz2NwQQMMTkoQIAgBIiNMwIEBAowhwGSECaAnBwAdPj4tFnzwQgAAAABJRU5ErkJggg==', '_default': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P8////fwAKAAP+j4hsjgAAAABJRU5ErkJggg==', }; var webgl_uniformlocations = {};
js/webgl.js
'use strict'; // Required args: base // Optional args: entity, offset-x, offset-y, offset-z function webgl_attach(args){ args = core_args({ 'args': args, 'defaults': { 'entity': '_webgl-camera', 'offset-x': 0, 'offset-y': 0, 'offset-z': 0, }, }); core_entities[args['entity']]['attach'] = { 'offset': { 'x': args['offset-x'], 'y': args['offset-y'], 'z': args['offset-z'], }, 'to': args['base'], }; } // Required args: entity // Optional args: axes function webgl_billboard(args){ args = core_args({ 'args': args, 'defaults': { 'axes': { 'y': 'y', }, }, }); for(var axis in args['axes']){ core_entities[args['entity']]['rotate'][axis] = 360 - core_entities['_webgl-camera']['rotate'][args['axes'][axis]]; } } // Required args: colorData, indexData, normalData, textureData, vertexData function webgl_buffer_set(args){ return { 'color': webgl_buffer_set_type({ 'data': args['colorData'], }), /* 'index': webgl_buffer_set_type({ 'data': args['indexData'], 'type': 'Uint16Array', }), */ 'normal': webgl_buffer_set_type({ 'data': args['normalData'], }), 'texture': webgl_buffer_set_type({ 'data': args['textureData'], }), 'vertex': webgl_buffer_set_type({ 'data': args['vertexData'], }), }; } // Required args: data // Optional args: type function webgl_buffer_set_type(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'Float32Array', }, }); var buffer = webgl_buffer.createBuffer(); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, buffer ); webgl_buffer.bufferData( webgl_buffer.ARRAY_BUFFER, new window[args['type']](args['data']), webgl_buffer.STATIC_DRAW ); return buffer; } function webgl_camera_first(){ if(core_mouse['pointerlock-state']){ webgl_camera_rotate({ 'x': core_mouse['movement-y'] / 10, 'y': core_mouse['movement-x'] / 10, }); } } // Optional args: speed, strafe, y function webgl_camera_move(args){ args = core_args({ 'args': args, 'defaults': { 'speed': 1, 'strafe': false, 'y': 0, }, }); var movement = math_move_3d({ 'angle': core_entities['_webgl-camera']['rotate']['y'], 'speed': args['speed'], 'strafe': args['strafe'], }); core_entities['_webgl-camera']['dx'] += movement['x']; core_entities['_webgl-camera']['dy'] += args['y']; core_entities['_webgl-camera']['dz'] += movement['z']; } // Optional args: x, xlock, y, z function webgl_camera_rotate(args){ args = core_args({ 'args': args, 'defaults': { 'x': 0, 'xlock': args['xlock'] !== false, 'y': 0, 'z': 0, }, }); var axes = { 'x': args['x'], 'y': args['y'], 'z': args['z'], }; for(var axis in axes){ core_entities['_webgl-camera']['rotate'][axis] = math_clamp({ 'max': 360, 'min': 0, 'value': math_round({ 'number': core_entities['_webgl-camera']['rotate'][axis] + axes[axis], }), 'wrap': true, }); } if(args['xlock']){ var max = 89; if(core_entities['_webgl-camera']['rotate']['x'] > 180){ max += 271; } core_entities['_webgl-camera']['rotate']['x'] = math_clamp({ 'max': max, 'min': max - 89, 'value': core_entities['_webgl-camera']['rotate']['x'], }); } for(var axis in axes){ core_entities['_webgl-camera']['rotate-radians'][axis] = math_degrees_to_radians({ 'degrees': core_entities['_webgl-camera']['rotate'][axis], }); } } // Required args: color function webgl_clearcolor_set(args){ webgl_properties['clearcolor'] = args['color']; webgl_buffer.clearColor( webgl_properties['clearcolor']['red'], webgl_properties['clearcolor']['green'], webgl_properties['clearcolor']['blue'], webgl_properties['clearcolor']['alpha'] ); } function webgl_draw(){ webgl_buffer.viewport( 0, 0, webgl_buffer.viewportWidth, webgl_buffer.viewportHeight ); webgl_buffer.clear(webgl_buffer.COLOR_BUFFER_BIT | webgl_buffer.DEPTH_BUFFER_BIT); math_matrix_identity({ 'id': 'camera', }); math_matrix_rotate({ 'dimensions': [ core_entities['_webgl-camera']['rotate-radians']['x'], core_entities['_webgl-camera']['rotate-radians']['y'], core_entities['_webgl-camera']['rotate-radians']['z'], ], 'id': 'camera', }); math_matrix_translate({ 'dimensions': [ core_entities['_webgl-camera']['position']['x'], core_entities['_webgl-camera']['position']['y'], core_entities['_webgl-camera']['position']['z'], ], 'id': 'camera', }); webgl_buffer.disable(webgl_buffer.DEPTH_TEST); core_group_modify({ 'groups': [ 'depthfalse', ], 'todo': function(entity){ webgl_draw_entity(entity); }, }); webgl_buffer.enable(webgl_buffer.DEPTH_TEST); core_group_modify({ 'groups': [ 'depthtrue', ], 'todo': function(entity){ if(core_entities[entity]['alpha'] === 1){ webgl_draw_entity(entity); } }, }); core_group_modify({ 'groups': [ 'depthtrue', ], 'todo': function(entity){ if(core_entities[entity]['alpha'] < 1){ webgl_draw_entity(entity); } }, }); webgl_canvas.clearRect( 0, 0, webgl_canvas_properties['width'], webgl_canvas_properties['height'] ); webgl_canvas.drawImage( document.getElementById('buffer'), 0, 0 ); for(var text in webgl_text){ Object.assign( webgl_canvas, webgl_text[text]['properties'] ); webgl_canvas.fillText( webgl_text[text]['text'], webgl_text[text]['x'], webgl_text[text]['y'] ); } if(webgl_properties['pointer'] !== false){ webgl_canvas.fillStyle = webgl_properties['pointer']; webgl_canvas.fillRect( webgl_canvas_properties['width-half'] - 1, webgl_canvas_properties['height-half'] - 1, 2, 2 ); } } function webgl_drawloop(){ if(!core_menu_open){ webgl_draw(); } webgl_animationFrame = window.requestAnimationFrame(webgl_drawloop); } function webgl_draw_entity(entity){ if(core_entities[entity]['draw'] === false){ return; } if(core_entities[entity]['billboard'] === true){ webgl_billboard({ 'entity': entity, }); } math_matrix_clone({ 'id': 'camera', 'to': 'cache', }); math_matrix_translate({ 'dimensions': [ -core_entities[entity]['position']['x'], -core_entities[entity]['position']['y'], -core_entities[entity]['position']['z'], ], 'id': 'camera', }); math_matrix_rotate({ 'dimensions': [ core_entities[entity]['rotate-radians']['x'], core_entities[entity]['rotate-radians']['y'], core_entities[entity]['rotate-radians']['z'], ], 'id': 'camera', }); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['normal'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexNormal'], 3, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['color'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexColor'], 4, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['vertex'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_vertexPosition'], 3, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['texture'] ); webgl_buffer.vertexAttribPointer( webgl_attributes['vec_texturePosition'], 2, webgl_buffer.FLOAT, false, 0, 0 ); webgl_buffer.activeTexture(webgl_buffer.TEXTURE0); webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, core_entities[entity]['texture'] ); webgl_buffer.uniform1i( webgl_uniformlocations['sampler'], 0 ); /* webgl_buffer.bindBuffer( webgl_buffer.ARRAY_BUFFER, core_entities[entity]['buffer']['index'] ); */ webgl_buffer.uniform1f( webgl_uniformlocations['alpha'], core_entities[entity]['alpha'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_normalMatrix'], 0, math_matrices['perspective'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_perspectiveMatrix'], 0, math_matrices['perspective'] ); webgl_buffer.uniformMatrix4fv( webgl_uniformlocations['mat_cameraMatrix'], 0, math_matrices['camera'] ); webgl_buffer.drawArrays( webgl_buffer[core_entities[entity]['mode']], 0, core_entities[entity]['vertices-length'] ); math_matrix_copy({ 'id': 'cache', 'to': 'camera', }); } // Optional args: ambient-blue, ambient-green, ambient-red, camera, clear-alpha, clear-blue, clear-green, clear_red, cleardepth, contextmenu, fog, grabity-acceleration, gravity-max, speed function webgl_init(args){ args = core_args({ 'args': args, 'defaults': { 'ambient-blue': 1, 'ambient-green': 1, 'ambient-red': 1, 'camera': 'free', 'clear-alpha': 1, 'clear-blue': 0, 'clear-green': 0, 'clear-red': 0, 'cleardepth': 1, 'contextmenu': true, 'direction-blue': 1, 'direction-green': 1, 'direction-red': 1, 'direction-vector': false, 'fog': -0.0001, 'gravity-acceleration': -0.05, 'gravity-max': -1, 'speed': .1, }, }); webgl_canvas_properties = { 'fillStyle': '#fff', 'font': webgl_fonts['medium'], 'height': 0, 'height-half': 0, 'lineJoin': 'miter', 'lineWidth': 1, 'strokeStyle': '#fff', 'textAlign': 'start', 'textBaseline': 'alphabetic', 'width': 0, 'width-half': 0, }; webgl_properties = { 'ambientlighting': { 'blue': args['ambient-blue'], 'green': args['ambient-green'], 'red': args['ambient-red'], }, 'camera': { 'speed': args['speed'], 'type': args['camera'], }, 'clearcolor': { 'alpha': args['clear-alpha'], 'blue': args['clear-blue'], 'green': args['clear-green'], 'red': args['clear-red'], }, 'cleardepth': args['cleardepth'], 'collision-range': 2.5, 'directionlighting': { 'blue': args['direction-blue'], 'green': args['direction-green'], 'red': args['direction-red'], 'vector': args['direction-vector'], }, 'fog': args['fog'], 'gravity': { 'acceleration': args['gravity-acceleration'], 'max': args['gravity-max'], }, 'pointer': false, }; var properties = ''; if(!args['contextmenu']){ properties = ' oncontextmenu="return false" '; } core_html({ 'parent': document.body, 'properties': { 'id': 'wrap', 'innerHTML': '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>', }, }); math_matrices['camera'] = math_matrix_create(); math_matrices['perspective'] = math_matrix_create(); webgl_buffer = document.getElementById('buffer').getContext( 'webgl', { 'alpha': false, 'antialias': true, 'depth': true, 'premultipliedAlpha': false, 'preserveDrawingBuffer': false, 'stencil': false, } ); webgl_canvas = document.getElementById('canvas').getContext('2d'); window.onresize = webgl_resize; webgl_resize(); webgl_clearcolor_set({ 'color': { 'alpha': webgl_properties['clearcolor']['alpha'], 'blue': webgl_properties['clearcolor']['blue'], 'green': webgl_properties['clearcolor']['green'], 'red': webgl_properties['clearcolor']['red'], }, }); webgl_buffer.clearDepth(webgl_properties['cleardepth']); webgl_buffer.enable(webgl_buffer.CULL_FACE); webgl_buffer.enable(webgl_buffer.DEPTH_TEST); webgl_shader_update(); webgl_buffer.blendFunc( webgl_buffer.SRC_ALPHA, webgl_buffer.ONE_MINUS_SRC_ALPHA ); webgl_buffer.enable(webgl_buffer.BLEND); core_entity_set({ 'default': true, 'groups': [ 'depthtrue', ], 'properties': { 'alpha': 1, 'attach': false, 'billboard': false, 'collides': false, 'collision': false, 'color': [], 'draw': true, 'dx': 0, 'dy': 0, 'dz': 0, 'gravity': false, /* 'index': [ 0, 1, 2, 0, 2, 3, ], */ 'mode': 'TRIANGLE_FAN', 'normals': [], 'position': { 'x': 0, 'y': 0, 'z': 0, }, 'rotate': { 'x': 0, 'y': 0, 'z': 0, }, 'rotate-radians': { 'x': 0, 'y': 0, 'z': 0, }, 'scale': { 'x': 1, 'y': 1, 'z': 1, }, 'textureData': [ 0, 1, 0, 0, 1, 0, 1, 1, ], 'vertices-length': 0, }, 'todo': function(entity){ core_entities[entity]['normals'] = webgl_normals({ 'x-rotation': core_entities[entity]['rotate']['x'], 'y-rotation': core_entities[entity]['rotate']['y'], 'z-rotation': core_entities[entity]['rotate']['z'], }); if(core_entities[entity]['draw'] === false){ return; } core_entities[entity]['rotate-radians'] = { 'x': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['x'], }), 'y': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['y'], }), 'z': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['z'], }), }; core_entities[entity]['vertices-length'] = core_entities[entity]['vertices'].length / 3; core_entities[entity]['buffer'] = webgl_buffer_set({ 'colorData': core_entities[entity]['color'], //'indexData': core_entities[entity]['index'], 'normalData': core_entities[entity]['normals'], 'textureData': core_entities[entity]['textureData'], 'vertexData': core_entities[entity]['vertices'], }); webgl_texture_set({ 'entityid': entity, 'image': webgl_textures['_default'], }); }, 'type': 'webgl', }); core_entity_create({ 'id': '_webgl-camera', 'properties': { 'collides': true, 'draw': false, 'gravity': webgl_properties['camera']['type'] === 'gravity', }, }); core_interval_modify({ 'id': 'webgl-interval', 'interval': core_storage_data['frame-ms'], 'paused': true, 'todo': webgl_logicloop, }); if(!core_menu_open){ webgl_setmode(); } } function webgl_logicloop(){ core_entities['_webgl-camera']['dx'] = 0; core_entities['_webgl-camera']['dz'] = 0; if(!core_entities['_webgl-camera']['gravity']){ core_entities['_webgl-camera']['dy'] = 0; } if(webgl_properties['camera']['type'] !== false){ if(core_keys[65]['state']){ webgl_camera_move({ 'speed': -webgl_properties['camera']['speed'], 'strafe': true, }); } if(core_keys[68]['state']){ webgl_camera_move({ 'speed': webgl_properties['camera']['speed'], 'strafe': true, }); } if(core_keys[83]['state']){ webgl_camera_move({ 'speed': webgl_properties['camera']['speed'], }); } if(core_keys[87]['state']){ webgl_camera_move({ 'speed': -webgl_properties['camera']['speed'], }); } if(webgl_properties['camera']['type'] === 'free'){ if(core_keys[32]['state']){ webgl_camera_move({ 'speed': 0, 'y': webgl_properties['camera']['speed'], }); } if(core_keys[67]['state']){ webgl_camera_move({ 'speed': 0, 'y': -webgl_properties['camera']['speed'], }); } } } logic(); core_group_modify({ 'groups': [ 'webgl', ], 'todo': function(entity){ if(core_entities[entity]['logic']){ core_entities[entity]['logic'](); } core_entities[entity]['rotate-radians'] = { 'x': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['x'], }), 'y': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['y'], }), 'z': math_degrees_to_radians({ 'degrees': core_entities[entity]['rotate']['z'], }), }; if(core_entities[entity]['gravity']){ core_entities[entity]['dy'] = Math.max( core_entities[entity]['dy'] + webgl_properties['gravity']['acceleration'], webgl_properties['gravity']['max'] ); } if(core_entities[entity]['collides']){ for(var other_entity in core_entities){ if(entity !== other_entity && core_entities[other_entity]['collision']){ webgl_normals_collision({ 'entity0id': entity, 'entity1id': other_entity, }); } } } if(core_entities[entity]['attach'] !== false){ var attachto = core_entities[core_entities[entity]['attach']['to']]; for(var axis in core_entities[entity]['position']){ core_entities[entity]['position'][axis] = attachto['position'][axis] + core_entities[entity]['attach']['offset'][axis]; } }else{ for(var axis in core_entities[entity]['position']){ core_entities[entity]['position'][axis] += core_entities[entity]['d' + axis]; } } }, }); } // Optional args: x-rotation, y-rotation, z-rotation function webgl_normals(args){ args = core_args({ 'args': args, 'defaults': { 'x-rotation': 0, 'y-rotation': 0, 'z-rotation': 0, }, }); var normal_x = 0; var normal_y = 0; var normal_z = 0; if(args['x-rotation'] !== 0){ normal_z = math_round({ 'number': Math.sin(math_degrees_to_radians({ 'degrees': args['x-rotation'], })), }); }else if(args['z-rotation'] !== 0){ normal_x = -math_round({ 'number': Math.sin(math_degrees_to_radians({ 'degrees': args['z-rotation'], })), }); }else{ normal_y = math_round({ 'number': Math.cos(math_degrees_to_radians({ 'degrees': args['y-rotation'], })), }); } return [ normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, normal_x, normal_y, normal_z, ]; } // Required args: entity0id, entity1id function webgl_normals_collision(args){ var entity0 = core_entities[args['entity0id']]; var entity1 = core_entities[args['entity1id']]; if(entity1['normals'][0] !== 0){ if(entity1['normals'][0] === 1 && entity0['dx'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] && entity0['position']['x'] <= entity1['position']['x'] + webgl_properties['collision-range'] && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] + 1 && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range'] - 1){ entity0['dx'] = 0; entity0['position']['x'] = entity1['position']['x'] + webgl_properties['collision-range']; } }else if(entity1['normals'][0] === -1 && entity0['dx'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] + 1 && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range'] - 1){ entity0['dx'] = 0; entity0['position']['x'] = entity1['position']['x'] - webgl_properties['collision-range']; } } } if(entity1['normals'][1] !== 0){ if(entity1['normals'][1] === 1 && entity0['dy'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['y'] >= entity1['position']['y'] && entity0['position']['y'] <= entity1['position']['y'] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range']){ entity0['dy'] = 0; entity0['position']['y'] = entity1['position']['y'] + webgl_properties['collision-range']; } }else if(entity1['normals'][1] === -1 && entity0['dy'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] && entity0['position']['y'] >= entity1['position']['y'] - webgl_properties['collision-range'] && entity0['position']['y'] <= entity1['position']['y'] && entity0['position']['z'] >= entity1['position']['z'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z'] + entity1['vertices'][8] + webgl_properties['collision-range']){ entity0['dy'] = 0; entity0['position']['y'] = entity1['position']['y'] - webgl_properties['collision-range']; } } } if(entity1['normals'][2] !== 0){ if(entity1['normals'][2] === 1 && entity0['dz'] < 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] + 1 && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] - 1 && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][8] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] && entity0['position']['z'] <= entity1['position']['z'] + webgl_properties['collision-range']){ entity0['dz'] = 0; entity0['position']['z'] = entity1['position']['z'] + webgl_properties['collision-range']; } }else if(entity1['normals'][2] === -1 && entity0['dz'] > 0){ if(entity0['position']['x'] >= entity1['position']['x'] + entity1['vertices'][3] - webgl_properties['collision-range'] + 1 && entity0['position']['x'] <= entity1['position']['x'] + entity1['vertices'][0] + webgl_properties['collision-range'] - 1 && entity0['position']['y'] > entity1['position']['y'] + entity1['vertices'][2] - webgl_properties['collision-range'] && entity0['position']['y'] < entity1['position']['y'] + entity1['vertices'][8] + webgl_properties['collision-range'] && entity0['position']['z'] >= entity1['position']['z'] - webgl_properties['collision-range'] && entity0['position']['z'] <= entity1['position']['z']){ entity0['dz'] = 0; entity0['position']['z'] = entity1['position']['z'] - webgl_properties['collision-range']; } } } } function webgl_perspective(){ math_matrices['perspective'][0] = webgl_canvas_properties['height'] / webgl_canvas_properties['width']; math_matrices['perspective'][5] = 1; math_matrices['perspective'][10] = -1; math_matrices['perspective'][11] = -1; math_matrices['perspective'][14] = -2; } // Required args: id, shaderlist function webgl_program_create(args){ var program = webgl_buffer.createProgram(); for(var shader in args['shaderlist']){ webgl_buffer.attachShader( program, args['shaderlist'][shader] ); } webgl_buffer.linkProgram(program); webgl_buffer.useProgram(program); return program; } function webgl_resize(){ var buffer = document.getElementById('buffer'); var canvas = document.getElementById('canvas'); webgl_canvas_properties['height'] = window.innerHeight; webgl_canvas_properties['height-half'] = webgl_canvas_properties['height'] / 2; buffer.height = webgl_canvas_properties['height']; canvas.height = webgl_canvas_properties['height']; webgl_canvas_properties['width'] = window.innerWidth; webgl_canvas_properties['width-half'] = webgl_canvas_properties['width'] / 2; buffer.width = webgl_canvas_properties['width']; canvas.width = webgl_canvas_properties['width']; webgl_buffer.viewportHeight = webgl_canvas_properties['height']; webgl_buffer.viewportWidth = webgl_canvas_properties['width']; webgl_buffer.viewport(0, 0, webgl_canvas_properties['height'], webgl_canvas_properties['width']); Object.assign( webgl_buffer, webgl_canvas_properties ); webgl_perspective(); core_call({ 'todo': 'resize_logic', }); } // Optional args: mode, newgame function webgl_setmode(args){ args = core_args({ 'args': args, 'defaults': { 'mode': 0, 'newgame': false, }, }); window.cancelAnimationFrame(webgl_animationFrame); core_storage_save(); core_entity_remove_all(); webgl_resize(); core_entities['_webgl-camera']['position'] = { 'x': 0, 'y': 0, 'z': 0, }; core_entities['_webgl-camera']['rotate'] = { 'x': 0, 'y': 0, 'z': 0, }; core_mode = args['mode']; core_call({ 'args': core_mode, 'todo': 'load_data', }); if(args['newgame']){ core_escape(); } webgl_animationFrame = window.requestAnimationFrame(webgl_drawloop); core_interval_resume_all(); } // Required args: properties function webgl_setcanvasproperties(args){ Object.assign( webgl_canvas_properties, args['properties'] ); Object.assign( webgl_buffer, args['properties'] ); } // Required args: id, source, type function webgl_shader_create(args){ var shader = webgl_buffer.createShader(args['type']); webgl_buffer.shaderSource( shader, args['source'] ); webgl_buffer.compileShader(shader); return shader; } function webgl_shader_update(){ var fogstring = webgl_properties['fog'] !== false ? ('mix(' + 'vec4(' + webgl_properties['clearcolor']['red'] + ',' + webgl_properties['clearcolor']['green'] + ',' + webgl_properties['clearcolor']['blue'] + ',' + webgl_properties['clearcolor']['alpha'] + '),' + 'vec_fragmentColor,' + 'clamp(exp(' + webgl_properties['fog'] + ' * float_fogDistance * float_fogDistance), 0.0, 1.0)' + ')') : 'vec_fragmentColor'; var fragment_shader = webgl_shader_create({ 'id': 'fragment', 'source': 'precision mediump float;' + 'uniform float alpha;' + 'uniform sampler2D sampler;' + 'varying float float_fogDistance;' + 'varying vec2 vec_textureCoord;' + 'varying vec3 vec_lighting;' + 'varying vec4 vec_fragmentColor;' + 'void main(void){' + 'gl_FragColor = ' + fogstring + ' * texture2D(sampler, vec_textureCoord) * vec4(vec_lighting, 1.0) * alpha;' + '}', 'type': webgl_buffer.FRAGMENT_SHADER, }); var directionstring = webgl_properties['directionlighting']['vector'] !== false ? (' + (vec3(' + webgl_properties['directionlighting']['red'] + ',' + webgl_properties['directionlighting']['green'] + ',' + webgl_properties['directionlighting']['blue'] + ') * max(dot(transformedNormal.xyz, normalize(vec3(' + webgl_properties['directionlighting']['vector'] + '))),0.0));') : ''; var vertex_shader = webgl_shader_create({ 'id': 'vertex', 'source': 'attribute vec2 vec_texturePosition;' + 'attribute vec3 vec_vertexNormal;' + 'attribute vec4 vec_vertexColor;' + 'attribute vec4 vec_vertexPosition;' + 'uniform mat4 mat_cameraMatrix;' + 'uniform mat4 mat_normalMatrix;' + 'uniform mat4 mat_perspectiveMatrix;' + 'varying float float_fogDistance;' + 'varying vec2 vec_textureCoord;' + 'varying vec3 vec_lighting;' + 'varying vec4 vec_fragmentColor;' + 'void main(void){' + 'gl_Position = mat_perspectiveMatrix * mat_cameraMatrix * vec_vertexPosition;' + 'float_fogDistance = length(gl_Position.xyz);' + 'vec_fragmentColor = vec_vertexColor;' + 'vec_textureCoord = vec_texturePosition;' + 'vec4 transformedNormal = mat_normalMatrix * vec4(vec_vertexNormal, 1.0);' + 'vec_lighting = vec3(' + webgl_properties['ambientlighting']['red'] + ',' + webgl_properties['ambientlighting']['green'] + ',' + webgl_properties['ambientlighting']['blue'] + ')' + directionstring + ';' + '}', 'type': webgl_buffer.VERTEX_SHADER, }); var program = webgl_program_create({ 'id': 'shaders', 'shaderlist': [ fragment_shader, vertex_shader, ], }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexColor', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexNormal', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_vertexPosition', 'program': program, }); webgl_vertexattribarray_set({ 'attribute': 'vec_texturePosition', 'program': program, }); webgl_uniformlocations = { 'alpha': webgl_buffer.getUniformLocation( program, 'alpha' ), 'mat_cameraMatrix': webgl_buffer.getUniformLocation( program, 'mat_cameraMatrix' ), 'mat_normalMatrix': webgl_buffer.getUniformLocation( program, 'mat_normalMatrix' ), 'mat_perspectiveMatrix': webgl_buffer.getUniformLocation( program, 'mat_perspectiveMatrix' ), 'sampler': webgl_buffer.getUniformLocation( program, 'sampler' ), }; webgl_buffer.deleteProgram(program); } // Optional args: color function webgl_skybox(args){ args = core_args({ 'args': args, 'defaults': { 'color': webgl_vertexcolorarray(), }, }); core_entity_create({ 'id': 'skybox-back', 'properties': { 'color': args['color'], 'rotate': { 'x': 270, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-back', 'offset-z': 5, }); core_entity_create({ 'id': 'skybox-front', 'properties': { 'color': args['color'], 'rotate': { 'x': 90, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-front', 'offset-z': -5, }); core_entity_create({ 'id': 'skybox-left', 'properties': { 'color': args['color'], 'rotate': { 'z': 270, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-left', 'offset-x': -5, }); core_entity_create({ 'id': 'skybox-right', 'properties': { 'color': args['color'], 'rotate': { 'z': 90, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-right', 'offset-x': 5, }); core_entity_create({ 'id': 'skybox-top', 'properties': { 'color': args['color'], 'rotate': { 'x': 180, }, 'vertices': [ 5, 0, -5, -5, 0, -5, -5, 0, 5, 5, 0, 5, ], }, }); webgl_attach({ 'base': '_webgl-camera', 'entity': 'skybox-top', 'offset-y': 5, }); core_group_move({ 'entities': [ 'skybox-back', 'skybox-front', 'skybox-left', 'skybox-right', 'skybox-top', ], 'from': 'depthtrue', 'to': 'depthfalse', }); } // Required args: entityid // Optional args: image function webgl_texture_set(args){ args = core_args({ 'args': args, 'defaults': { 'image': webgl_textures['_default'], }, }); core_entities[args['entityid']]['texture'] = webgl_buffer.createTexture(); core_entities[args['entityid']]['image'] = core_image({ 'id': args['entityid'] + '-texture', 'src': args['image'], 'todo': function(){ webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, core_entities[args['entityid']]['texture'] ); webgl_buffer.texImage2D( webgl_buffer.TEXTURE_2D, 0, webgl_buffer.RGBA, webgl_buffer.RGBA, webgl_buffer.UNSIGNED_BYTE, core_entities[args['entityid']]['image'] ); webgl_buffer.texParameteri( webgl_buffer.TEXTURE_2D, webgl_buffer.TEXTURE_MAG_FILTER, webgl_buffer.NEAREST ); webgl_buffer.texParameteri( webgl_buffer.TEXTURE_2D, webgl_buffer.TEXTURE_MIN_FILTER, webgl_buffer.NEAREST ); webgl_buffer.bindTexture( webgl_buffer.TEXTURE_2D, void 0 ); }, }); } // Optional args: id, quality, type function webgl_uri(args){ args = core_args({ 'args': args, 'defaults': { 'id': 'buffer', 'quality': 1, 'type': 'image/png', }, }); return document.getElementById(args['id']).toDataURL( args['type'], args['quality'] ); } // Required args: attribute, program function webgl_vertexattribarray_set(args){ webgl_attributes[args['attribute']] = webgl_buffer.getAttribLocation( args['program'], args['attribute'] ); webgl_buffer.enableVertexAttribArray(webgl_attributes[args['attribute']]); } // Optional args: rgbarray, vertexcount function webgl_vertexcolorarray(args){ args = core_args({ 'args': args, 'defaults': { 'rgbarray': [ core_random_rgb(), core_random_rgb(), core_random_rgb(), core_random_rgb(), ], 'vertexcount': 4, }, }); while(args['rgbarray'].length < args['vertexcount']){ args['rgbarray'].push(args['rgbarray'][0]); } var color = []; for(var i = 0; i < args['vertexcount']; i++){ color.push( args['rgbarray'][i]['red'] / 256, args['rgbarray'][i]['green'] / 256, args['rgbarray'][i]['blue'] / 256, 1, ); } return color; } var webgl_animationFrame = 0; var webgl_attributes = {}; var webgl_buffer = 0; var webgl_canvas = 0; var webgl_fonts = { 'big': '300% monospace', 'medium': '200% monospace', 'small': '100% monospace', }; var webgl_canvas_properties = {}; var webgl_properties = {}; var webgl_text = {}; var webgl_textures = { '_debug': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAD1BMVEUAAP8A/wD/AAAAAAD///8hKtLYAAAAIklEQVQoz2NwQQMMTkoQIAgBIiNMwIEBAowhwGSECaAnBwAdPj4tFnzwQgAAAABJRU5ErkJggg==', '_default': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P8////fwAKAAP+j4hsjgAAAABJRU5ErkJggg==', }; var webgl_uniformlocations = {};
moved webgl group modify todo to separate function
js/webgl.js
moved webgl group modify todo to separate function
<ide><path>s/webgl.js <ide> 'webgl', <ide> ], <ide> 'todo': function(entity){ <del> if(core_entities[entity]['logic']){ <del> core_entities[entity]['logic'](); <del> } <del> <del> core_entities[entity]['rotate-radians'] = { <del> 'x': math_degrees_to_radians({ <del> 'degrees': core_entities[entity]['rotate']['x'], <del> }), <del> 'y': math_degrees_to_radians({ <del> 'degrees': core_entities[entity]['rotate']['y'], <del> }), <del> 'z': math_degrees_to_radians({ <del> 'degrees': core_entities[entity]['rotate']['z'], <del> }), <del> }; <del> <del> if(core_entities[entity]['gravity']){ <del> core_entities[entity]['dy'] = Math.max( <del> core_entities[entity]['dy'] + webgl_properties['gravity']['acceleration'], <del> webgl_properties['gravity']['max'] <del> ); <del> } <del> <del> if(core_entities[entity]['collides']){ <del> for(var other_entity in core_entities){ <del> if(entity !== other_entity <del> && core_entities[other_entity]['collision']){ <del> webgl_normals_collision({ <del> 'entity0id': entity, <del> 'entity1id': other_entity, <del> }); <del> } <del> } <del> } <del> <del> if(core_entities[entity]['attach'] !== false){ <del> var attachto = core_entities[core_entities[entity]['attach']['to']]; <del> for(var axis in core_entities[entity]['position']){ <del> core_entities[entity]['position'][axis] = attachto['position'][axis] + core_entities[entity]['attach']['offset'][axis]; <del> } <del> <del> }else{ <del> for(var axis in core_entities[entity]['position']){ <del> core_entities[entity]['position'][axis] += core_entities[entity]['d' + axis]; <del> } <del> } <del> }, <del> }); <add> webgl_logicloop_handle_entity(entity); <add> }, <add> }); <add>} <add> <add>function webgl_logicloop_handle_entity(entity){ <add> if(core_entities[entity]['logic']){ <add> core_entities[entity]['logic'](); <add> } <add> <add> core_entities[entity]['rotate-radians'] = { <add> 'x': math_degrees_to_radians({ <add> 'degrees': core_entities[entity]['rotate']['x'], <add> }), <add> 'y': math_degrees_to_radians({ <add> 'degrees': core_entities[entity]['rotate']['y'], <add> }), <add> 'z': math_degrees_to_radians({ <add> 'degrees': core_entities[entity]['rotate']['z'], <add> }), <add> }; <add> <add> if(core_entities[entity]['gravity']){ <add> core_entities[entity]['dy'] = Math.max( <add> core_entities[entity]['dy'] + webgl_properties['gravity']['acceleration'], <add> webgl_properties['gravity']['max'] <add> ); <add> } <add> <add> if(core_entities[entity]['collides']){ <add> for(var other_entity in core_entities){ <add> if(entity !== other_entity <add> && core_entities[other_entity]['collision']){ <add> webgl_normals_collision({ <add> 'entity0id': entity, <add> 'entity1id': other_entity, <add> }); <add> } <add> } <add> } <add> <add> if(core_entities[entity]['attach'] !== false){ <add> var attachto = core_entities[core_entities[entity]['attach']['to']]; <add> for(var axis in core_entities[entity]['position']){ <add> core_entities[entity]['position'][axis] = attachto['position'][axis] + core_entities[entity]['attach']['offset'][axis]; <add> } <add> <add> }else{ <add> for(var axis in core_entities[entity]['position']){ <add> core_entities[entity]['position'][axis] += core_entities[entity]['d' + axis]; <add> } <add> } <ide> } <ide> <ide> // Optional args: x-rotation, y-rotation, z-rotation
Java
apache-2.0
71228eb7004641059e508fa16511848d26e5303d
0
searchisko/searchisko,ollyjshaw/searchisko,searchisko/searchisko,ollyjshaw/searchisko,searchisko/searchisko,ollyjshaw/searchisko
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. */ package org.searchisko.api.service; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.format.DateTimeFormatter; import org.elasticsearch.common.joda.time.format.ISODateTimeFormat; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.RangeFilterBuilder; import org.elasticsearch.index.query.TermsFilterBuilder; import org.searchisko.api.model.ParsableIntervalConfig; import org.searchisko.api.model.QuerySettings; import org.searchisko.api.rest.search.ConfigParseUtil; import org.searchisko.api.rest.search.SemiParsedFilterConfig; import org.searchisko.api.rest.search.SemiParsedFilterConfigSupportSuppressed; import org.searchisko.api.rest.search.SemiParsedRangeFilterConfig; import org.searchisko.api.rest.search.SemiParsedTermsFilterConfig; /** * Service that can prepare and cache parsed configuration of filters and search filters for the request. * In order to prepare the cache the * {@link ParsedFilterConfigService#prepareFiltersForRequest(org.searchisko.api.model.QuerySettings.Filters)} method * must be called first. * * @author Lukas Vlcek * @since 1.0.2 */ @Named @RequestScoped public class ParsedFilterConfigService { @Inject protected Logger log; @Inject protected ConfigService configService; private static final DateTimeFormatter DATE_TIME_FORMATTER_UTC = ISODateTimeFormat.dateTime().withZoneUTC(); // <filter name, config> private Map<String, SemiParsedFilterConfig> semiParsedFilters = null; // <field name, filter builder> private Map<String, FilterBuilder> searchFilters = null; // <field name, interval range> private Map<String, IntervalRange> rangeFiltersIntervals = null; public class IntervalRange { private DateTime gte; private DateTime lte; public DateTime getGte() {return gte; } public void setGte(DateTime value) { this.gte = value; } public DateTime getLte() {return lte; } public void setLte(DateTime value) { this.lte = value; } } /** * Prepares cache of parsed filter configurations and search filters valid for actual request. * This method should be called as soon as {@link QuerySettings.Filters} is * available. * * @param filters to use to prepare relevant parsed filter configurations into request scope * @throws java.lang.ReflectiveOperationException if filter field configuration file can not be parsed correctly */ protected void prepareFiltersForRequest(QuerySettings.Filters filters) throws ReflectiveOperationException { semiParsedFilters = new LinkedHashMap<>(); searchFilters = new LinkedHashMap<>(); rangeFiltersIntervals = new LinkedHashMap<>(); if (filters != null && !filters.getFilterCandidatesKeys().isEmpty()) { Map<String, Object> filtersConfig = configService.get(ConfigService.CFGNAME_SEARCH_FULLTEXT_FILTER_FIELDS); if (filtersConfig == null || (filtersConfig != null && filtersConfig.isEmpty())) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Configuration document [" + ConfigService.CFGNAME_SEARCH_FULLTEXT_FILTER_FIELDS + "] not found or is empty! This might be a bug."); } return; } // collect parsed filter configurations that are relevant to filters required by client for (String filterCandidateKey : filters.getFilterCandidatesKeys()) { if (filtersConfig.containsKey(filterCandidateKey)) { // get filter types for filterCandidateKey and check all types are the same Object filterConfig = filtersConfig.get(filterCandidateKey); SemiParsedFilterConfig parsedFilterConfig = ConfigParseUtil.parseFilterType(filterConfig, filterCandidateKey); // TODO get from cache? semiParsedFilters.put(filterCandidateKey, parsedFilterConfig); } } // iterate over all collected filters and drop those that are suppressed for (String filterName : semiParsedFilters.keySet().toArray(new String[semiParsedFilters.size()])) { // parsed filters could have been removed in the meantime so we check if it is still present if (semiParsedFilters.containsKey(filterName)) { SemiParsedFilterConfig parsedFilterConfig = semiParsedFilters.get(filterName); if (parsedFilterConfig instanceof SemiParsedFilterConfigSupportSuppressed) { List<String> suppressed = ((SemiParsedFilterConfigSupportSuppressed) parsedFilterConfig).getSuppressed(); if (suppressed != null) { for (String suppress : suppressed) { if (semiParsedFilters.containsKey(suppress)) { semiParsedFilters.remove(suppress); } } } } } } // iterate over filters for (SemiParsedFilterConfig filterConfig : semiParsedFilters.values()) { // terms filter if (filterConfig instanceof SemiParsedTermsFilterConfig) { SemiParsedTermsFilterConfig conf = (SemiParsedTermsFilterConfig) filterConfig; Set<String> fn = this.getFilterNamesForDocumentField(conf.getFieldName()); final List<String> filterValues = new ArrayList<>(filters.getFilterCandidateValues(fn)); if (!filterValues.isEmpty()) { // handle <_lowercase> if specified if (conf.isLowercase()) { for (int i = 0; i < filterValues.size(); i++) { filterValues.set(i, filterValues.get(i).toLowerCase(Locale.ENGLISH)); } } TermsFilterBuilder tfb = new TermsFilterBuilder(conf.getFieldName(), filterValues); // handle terms filter <optional_settings> if (conf.getName() != null) { tfb.filterName(conf.getName()); } if (conf.isCache() != null) { tfb.cache(conf.isCache()); } if (conf.isCache() != null && conf.isCache() && conf.getCacheKey() != null) { tfb.cacheKey(conf.getCacheKey()); } // TODO handle tfb.execution() searchFilters.put(conf.getFieldName(), tfb); } // range filter } else if (filterConfig instanceof SemiParsedRangeFilterConfig) { SemiParsedRangeFilterConfig conf = (SemiParsedRangeFilterConfig) filterConfig; RangeFilterBuilder rfb; // check if there is already range filter for this document field if (searchFilters.containsKey(conf.getFieldName()) && searchFilters.get(conf.getFieldName()) instanceof RangeFilterBuilder) { // in this case we will be adding (or overriding) settings of existing filter rfb = (RangeFilterBuilder) searchFilters.get(conf.getFieldName()); } else { rfb = new RangeFilterBuilder(conf.getFieldName()); } final String filterValue = filters.getFirstValueForFilterCandidate(conf.getFilterName()); ParsableIntervalConfig interval = null; if (filterValue != null) { IntervalRange intervalRange = rangeFiltersIntervals.get(conf.getFieldName()); if (intervalRange == null) { intervalRange = new IntervalRange(); rangeFiltersIntervals.put(conf.getFieldName(),intervalRange); } // handle <_processor> if specified if (conf.getProcessor() != null) { Class<?> processorClass = Class.forName(conf.getProcessor()); if (!processorClass.isEnum()) { throw new RuntimeException("Class [" + conf.getProcessor() + "] is not an enum type."); } // TODO: improve ParsableIntervalConfig design to make sure this method has to be implemented Method m = processorClass.getMethod("parseRequestParameterValue", String.class); interval = (ParsableIntervalConfig) m.invoke(processorClass, filterValue); } if (conf.definesGte()) { if (interval != null) { DateTime gte = new DateTime(interval.getGteValue(System.currentTimeMillis())); rfb.gte(gte.toString(DATE_TIME_FORMATTER_UTC)); intervalRange.setGte(gte); } else { rfb.gte(filterValue); intervalRange.setGte(DATE_TIME_FORMATTER_UTC.parseDateTime(filterValue)); } } else if (conf.definesLte()) { if (interval != null) { DateTime lte = new DateTime(interval.getLteValue(System.currentTimeMillis())); rfb.lte(lte.toString(DATE_TIME_FORMATTER_UTC)); intervalRange.setLte(lte); } else { rfb.lte(filterValue); intervalRange.setLte(DATE_TIME_FORMATTER_UTC.parseDateTime(filterValue)); } } } // handle range filter <optional_settings> if (conf.getName() != null) { rfb.filterName(conf.getName()); } if (conf.isCache() != null) { rfb.cache(conf.isCache()); } if (conf.isCache() != null && conf.isCache() && conf.getCacheKey() != null) { rfb.cacheKey(conf.getCacheKey()); } searchFilters.put(conf.getFieldName(), rfb); } else { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Unsupported SemiParsedFilterConfig type: " + filterConfig.getClass().getName()); } } } } } /** * Provide all valid filter configurations relevant to current request. * Keys of returned map represent filter names of filter configurations for current request. * * @return map of {@link org.searchisko.api.rest.search.SemiParsedFilterConfig}s for current request * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, SemiParsedFilterConfig> getFilterConfigsForRequest() { if (semiParsedFilters == null) { // this should not happen if request filters have been initialized correctly before throw new RuntimeException("Parsed filters not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return semiParsedFilters; } /** * Provide all valid search filters relevant to current request. * Keys of returned map represent document field name the search filter executes on. * * @return map of {@link org.elasticsearch.index.query.FilterBuilder}s for current request * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, FilterBuilder> getSearchFiltersForRequest() { if (searchFilters == null) { // this should not happen if request filters have been initialized correctly before throw new RuntimeException("Search filters not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return searchFilters; } /** * Provides all valid interval ranges relevant to current request. * Keys of returned map represent document field name. * * @return * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, IntervalRange> getRangeFiltersIntervals() { if (rangeFiltersIntervals == null) { // this should not happen if range filter intervals have been initialized correctly before throw new RuntimeException("Range filter intervals not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return rangeFiltersIntervals; } /** * Return set of filter names configured to work on top of given field name. * * @param fieldName * @return Set of filter names * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Set<String> getFilterNamesForDocumentField(String fieldName) { Set<String> filterNames = new HashSet<>(); for (SemiParsedFilterConfig c : this.getFilterConfigsForRequest().values()) { if (c.getFieldName().equals(fieldName)) { filterNames.add(c.getFilterName()); } } return filterNames; } /** * @return true if cache of {@link org.searchisko.api.rest.search.SemiParsedFilterConfig}s and * {@link org.elasticsearch.index.query.FilterBuilder}s has been initialized */ public boolean isCacheInitialized() { return (semiParsedFilters == null || searchFilters == null) ? false: true; } }
api/src/main/java/org/searchisko/api/service/ParsedFilterConfigService.java
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. */ package org.searchisko.api.service; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.joda.time.format.DateTimeFormatter; import org.elasticsearch.common.joda.time.format.ISODateTimeFormat; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.RangeFilterBuilder; import org.elasticsearch.index.query.TermsFilterBuilder; import org.searchisko.api.model.ParsableIntervalConfig; import org.searchisko.api.model.QuerySettings; import org.searchisko.api.rest.search.*; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Service that can prepare and cache parsed configuration of filters and search filters for the request. * In order to prepare the cache the * {@link ParsedFilterConfigService#prepareFiltersForRequest(org.searchisko.api.model.QuerySettings.Filters)} method * must be called first. * * @author Lukas Vlcek * @since 1.0.2 */ @Named @RequestScoped public class ParsedFilterConfigService { @Inject protected Logger log; @Inject protected ConfigService configService; private static final DateTimeFormatter DATE_TIME_FORMATTER_UTC = ISODateTimeFormat.dateTime().withZoneUTC(); // <filter name, config> private Map<String, SemiParsedFilterConfig> semiParsedFilters = null; // <field name, filter builder> private Map<String, FilterBuilder> searchFilters = null; // <field name, interval range> private Map<String, IntervalRange> rangeFiltersIntervals = null; public class IntervalRange { private DateTime gte; private DateTime lte; public DateTime getGte() {return gte; } public void setGte(DateTime value) { this.gte = value; } public DateTime getLte() {return lte; } public void setLte(DateTime value) { this.lte = value; } } /** * Prepares cache of parsed filter configurations and search filters valid for actual request. * This method should be called as soon as {@link QuerySettings.Filters} is * available. * * @param filters to use to prepare relevant parsed filter configurations into request scope * @throws java.lang.ReflectiveOperationException if filter field configuration file can not be parsed correctly */ protected void prepareFiltersForRequest(QuerySettings.Filters filters) throws ReflectiveOperationException { semiParsedFilters = new LinkedHashMap<>(); searchFilters = new LinkedHashMap<>(); rangeFiltersIntervals = new LinkedHashMap<>(); if (filters != null && !filters.getFilterCandidatesKeys().isEmpty()) { Map<String, Object> filtersConfig = configService.get(ConfigService.CFGNAME_SEARCH_FULLTEXT_FILTER_FIELDS); if (filtersConfig == null || (filtersConfig != null && filtersConfig.isEmpty())) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Configuration document [" + ConfigService.CFGNAME_SEARCH_FULLTEXT_FILTER_FIELDS + "] not found or is empty! This might be a bug."); } return; } // collect parsed filter configurations that are relevant to filters required by client for (String filterCandidateKey : filters.getFilterCandidatesKeys()) { if (filtersConfig.containsKey(filterCandidateKey)) { // get filter types for filterCandidateKey and check all types are the same Object filterConfig = filtersConfig.get(filterCandidateKey); SemiParsedFilterConfig parsedFilterConfig = ConfigParseUtil.parseFilterType(filterConfig, filterCandidateKey); // TODO get from cache? semiParsedFilters.put(filterCandidateKey, parsedFilterConfig); } } // iterate over all collected filters and drop those that are suppressed for (String filterName : semiParsedFilters.keySet()) { // parsed filters could have been removed in the meantime so we check if it is still present if (semiParsedFilters.containsKey(filterName)) { SemiParsedFilterConfig parsedFilterConfig = semiParsedFilters.get(filterName); if (parsedFilterConfig instanceof SemiParsedFilterConfigSupportSuppressed) { List<String> suppressed = ((SemiParsedFilterConfigSupportSuppressed) parsedFilterConfig).getSuppressed(); if (suppressed != null) { for (String suppress : suppressed) { if (semiParsedFilters.containsKey(suppress)) { semiParsedFilters.remove(suppress); } } } } } } // iterate over filters for (SemiParsedFilterConfig filterConfig : semiParsedFilters.values()) { // terms filter if (filterConfig instanceof SemiParsedTermsFilterConfig) { SemiParsedTermsFilterConfig conf = (SemiParsedTermsFilterConfig) filterConfig; Set<String> fn = this.getFilterNamesForDocumentField(conf.getFieldName()); final List<String> filterValues = new ArrayList<>(filters.getFilterCandidateValues(fn)); if (!filterValues.isEmpty()) { // handle <_lowercase> if specified if (conf.isLowercase()) { for (int i = 0; i < filterValues.size(); i++) { filterValues.set(i, filterValues.get(i).toLowerCase(Locale.ENGLISH)); } } TermsFilterBuilder tfb = new TermsFilterBuilder(conf.getFieldName(), filterValues); // handle terms filter <optional_settings> if (conf.getName() != null) { tfb.filterName(conf.getName()); } if (conf.isCache() != null) { tfb.cache(conf.isCache()); } if (conf.isCache() != null && conf.isCache() && conf.getCacheKey() != null) { tfb.cacheKey(conf.getCacheKey()); } // TODO handle tfb.execution() searchFilters.put(conf.getFieldName(), tfb); } // range filter } else if (filterConfig instanceof SemiParsedRangeFilterConfig) { SemiParsedRangeFilterConfig conf = (SemiParsedRangeFilterConfig) filterConfig; RangeFilterBuilder rfb; // check if there is already range filter for this document field if (searchFilters.containsKey(conf.getFieldName()) && searchFilters.get(conf.getFieldName()) instanceof RangeFilterBuilder) { // in this case we will be adding (or overriding) settings of existing filter rfb = (RangeFilterBuilder) searchFilters.get(conf.getFieldName()); } else { rfb = new RangeFilterBuilder(conf.getFieldName()); } final String filterValue = filters.getFirstValueForFilterCandidate(conf.getFilterName()); ParsableIntervalConfig interval = null; if (filterValue != null) { IntervalRange intervalRange = rangeFiltersIntervals.get(conf.getFieldName()); if (intervalRange == null) { intervalRange = new IntervalRange(); rangeFiltersIntervals.put(conf.getFieldName(),intervalRange); } // handle <_processor> if specified if (conf.getProcessor() != null) { Class<?> processorClass = Class.forName(conf.getProcessor()); if (!processorClass.isEnum()) { throw new RuntimeException("Class [" + conf.getProcessor() + "] is not an enum type."); } // TODO: improve ParsableIntervalConfig design to make sure this method has to be implemented Method m = processorClass.getMethod("parseRequestParameterValue", String.class); interval = (ParsableIntervalConfig) m.invoke(processorClass, filterValue); } if (conf.definesGte()) { if (interval != null) { DateTime gte = new DateTime(interval.getGteValue(System.currentTimeMillis())); rfb.gte(gte.toString(DATE_TIME_FORMATTER_UTC)); intervalRange.setGte(gte); } else { rfb.gte(filterValue); intervalRange.setGte(DATE_TIME_FORMATTER_UTC.parseDateTime(filterValue)); } } else if (conf.definesLte()) { if (interval != null) { DateTime lte = new DateTime(interval.getLteValue(System.currentTimeMillis())); rfb.lte(lte.toString(DATE_TIME_FORMATTER_UTC)); intervalRange.setLte(lte); } else { rfb.lte(filterValue); intervalRange.setLte(DATE_TIME_FORMATTER_UTC.parseDateTime(filterValue)); } } } // handle range filter <optional_settings> if (conf.getName() != null) { rfb.filterName(conf.getName()); } if (conf.isCache() != null) { rfb.cache(conf.isCache()); } if (conf.isCache() != null && conf.isCache() && conf.getCacheKey() != null) { rfb.cacheKey(conf.getCacheKey()); } searchFilters.put(conf.getFieldName(), rfb); } else { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Unsupported SemiParsedFilterConfig type: " + filterConfig.getClass().getName()); } } } } } /** * Provide all valid filter configurations relevant to current request. * Keys of returned map represent filter names of filter configurations for current request. * * @return map of {@link org.searchisko.api.rest.search.SemiParsedFilterConfig}s for current request * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, SemiParsedFilterConfig> getFilterConfigsForRequest() { if (semiParsedFilters == null) { // this should not happen if request filters have been initialized correctly before throw new RuntimeException("Parsed filters not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return semiParsedFilters; } /** * Provide all valid search filters relevant to current request. * Keys of returned map represent document field name the search filter executes on. * * @return map of {@link org.elasticsearch.index.query.FilterBuilder}s for current request * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, FilterBuilder> getSearchFiltersForRequest() { if (searchFilters == null) { // this should not happen if request filters have been initialized correctly before throw new RuntimeException("Search filters not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return searchFilters; } /** * Provides all valid interval ranges relevant to current request. * Keys of returned map represent document field name. * * @return * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Map<String, IntervalRange> getRangeFiltersIntervals() { if (rangeFiltersIntervals == null) { // this should not happen if range filter intervals have been initialized correctly before throw new RuntimeException("Range filter intervals not initialized yet. New request filters need to be " + "initialized via prepareFiltersForRequest() method. This is probably an implementation error."); } return rangeFiltersIntervals; } /** * Return set of filter names configured to work on top of given field name. * * @param fieldName * @return Set of filter names * @throws java.lang.RuntimeException if new request filters cache hasn't been initialized yet */ public Set<String> getFilterNamesForDocumentField(String fieldName) { Set<String> filterNames = new HashSet<>(); for (SemiParsedFilterConfig c : this.getFilterConfigsForRequest().values()) { if (c.getFieldName().equals(fieldName)) { filterNames.add(c.getFilterName()); } } return filterNames; } /** * @return true if cache of {@link org.searchisko.api.rest.search.SemiParsedFilterConfig}s and * {@link org.elasticsearch.index.query.FilterBuilder}s has been initialized */ public boolean isCacheInitialized() { return (semiParsedFilters == null || searchFilters == null) ? false: true; } }
fixed ConcurrentModificationException during iterating and manipulating the map. fixes #136
api/src/main/java/org/searchisko/api/service/ParsedFilterConfigService.java
fixed ConcurrentModificationException during iterating and manipulating the map. fixes #136
<ide><path>pi/src/main/java/org/searchisko/api/service/ParsedFilterConfigService.java <ide> * as indicated by the @authors tag. All rights reserved. <ide> */ <ide> package org.searchisko.api.service; <add> <add>import java.lang.reflect.Method; <add>import java.util.ArrayList; <add>import java.util.HashSet; <add>import java.util.LinkedHashMap; <add>import java.util.List; <add>import java.util.Locale; <add>import java.util.Map; <add>import java.util.Set; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <add> <add>import javax.enterprise.context.RequestScoped; <add>import javax.inject.Inject; <add>import javax.inject.Named; <ide> <ide> import org.elasticsearch.common.joda.time.DateTime; <ide> import org.elasticsearch.common.joda.time.format.DateTimeFormatter; <ide> import org.elasticsearch.index.query.TermsFilterBuilder; <ide> import org.searchisko.api.model.ParsableIntervalConfig; <ide> import org.searchisko.api.model.QuerySettings; <del>import org.searchisko.api.rest.search.*; <del> <del>import javax.enterprise.context.RequestScoped; <del>import javax.inject.Inject; <del>import javax.inject.Named; <del>import java.lang.reflect.Method; <del>import java.util.*; <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <add>import org.searchisko.api.rest.search.ConfigParseUtil; <add>import org.searchisko.api.rest.search.SemiParsedFilterConfig; <add>import org.searchisko.api.rest.search.SemiParsedFilterConfigSupportSuppressed; <add>import org.searchisko.api.rest.search.SemiParsedRangeFilterConfig; <add>import org.searchisko.api.rest.search.SemiParsedTermsFilterConfig; <ide> <ide> /** <ide> * Service that can prepare and cache parsed configuration of filters and search filters for the request. <ide> } <ide> <ide> // iterate over all collected filters and drop those that are suppressed <del> for (String filterName : semiParsedFilters.keySet()) { <add> for (String filterName : semiParsedFilters.keySet().toArray(new String[semiParsedFilters.size()])) { <ide> // parsed filters could have been removed in the meantime so we check if it is still present <ide> if (semiParsedFilters.containsKey(filterName)) { <ide> SemiParsedFilterConfig parsedFilterConfig = semiParsedFilters.get(filterName);
Java
mit
b84b230801a34055a19a6d0e5a862436864243b4
0
cobaltians/Cobalt-Android
/** * * CobaltImageCache * Cobalt * * The MIT License (MIT) * * Copyright (c) 2014 Cobaltians * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.cobaltians.cobalt.database; import org.cobaltians.cobalt.Cobalt; import android.graphics.Bitmap; import android.util.Base64; import android.util.Log; import java.io.ByteArrayOutputStream; import java.util.Hashtable; public class CobaltImageCache { private static final String TAG = CobaltImageCache.class.getSimpleName(); private static CobaltImageCache sInstance; private Hashtable<String, Bitmap> mMapImages; private CobaltImageCache() { mMapImages = new Hashtable<> (); } public static CobaltImageCache getInstance() { if (sInstance == null) { sInstance = new CobaltImageCache(); } return sInstance; } public void setImage(String id, Bitmap image) { if (id != null && image != null) { mMapImages.put(id, image); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - setImage: id and image could not be null!"); } public Bitmap getImage(String id) { if (id != null) { return mMapImages.get(id); } else { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - getImage: id could not be null!"); return null; } } public String toBase64(String id) { String encodeImage = null; if (id != null) { Bitmap bitmap = mMapImages.get(id); if (bitmap != null) { int quality = 100; //need this loop cause with some new device the length of url exceed 2097152 characters and fail upload do { // compressing the image ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); // encode image encodeImage = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP); quality -= 1; } while (encodeImage.length() > 2097152); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - toBase64: id could not be null!"); return encodeImage; } }
src/main/java/org/cobaltians/cobalt/database/CobaltImageCache.java
/** * * CobaltImageCache * Cobalt * * The MIT License (MIT) * * Copyright (c) 2014 Cobaltians * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.cobaltians.cobalt.database; import org.cobaltians.cobalt.Cobalt; import android.graphics.Bitmap; import android.util.Base64; import android.util.Log; import java.io.ByteArrayOutputStream; import java.util.Hashtable; public class CobaltImageCache { private static final String TAG = CobaltImageCache.class.getSimpleName(); private static CobaltImageCache sInstance; private Hashtable<String, Bitmap> mMapImages; private CobaltImageCache() { mMapImages = new Hashtable<> (); } public static CobaltImageCache getInstance() { if (sInstance == null) { sInstance = new CobaltImageCache(); } return sInstance; } public void setImage(String id, Bitmap image) { if (id != null && image != null) { mMapImages.put(id, image); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - setImage: id and image could not be null!"); } public Bitmap getImage(String id) { if (id != null) { return mMapImages.get(id); } else { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - getImage: id could not be null!"); return null; } } public String toBase64(String id) { String encodeImage = null; if (id != null) { Bitmap bitmap = mMapImages.get(id); if (bitmap != null) { // compressing the image ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // encode image encodeImage = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - toBase64: id could not be null!"); return encodeImage; } }
fix url exceed with image upload
src/main/java/org/cobaltians/cobalt/database/CobaltImageCache.java
fix url exceed with image upload
<ide><path>rc/main/java/org/cobaltians/cobalt/database/CobaltImageCache.java <ide> Bitmap bitmap = mMapImages.get(id); <ide> <ide> if (bitmap != null) { <del> // compressing the image <del> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <del> bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); <del> // encode image <del> encodeImage = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP); <add> int quality = 100; <add> //need this loop cause with some new device the length of url exceed 2097152 characters and fail upload <add> do { <add> // compressing the image <add> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <add> bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); <add> // encode image <add> encodeImage = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP); <add> quality -= 1; <add> } <add> while (encodeImage.length() > 2097152); <ide> } <ide> } <ide> else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - toBase64: id could not be null!");
Java
apache-2.0
b0549ff256ffb1e2abc95c2f33ef7b1da55cc890
0
zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services
package org.sagebionetworks.client; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import org.sagebionetworks.client.exceptions.SynapseClientException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.client.exceptions.SynapseResultNotReadyException; import org.sagebionetworks.client.exceptions.SynapseTableUnavailableException; import org.sagebionetworks.client.exceptions.SynapseTermsOfUseException; import org.sagebionetworks.downloadtools.FileUtils; import org.sagebionetworks.evaluation.model.BatchUploadResponse; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.Submission; import org.sagebionetworks.evaluation.model.SubmissionBundle; import org.sagebionetworks.evaluation.model.SubmissionContributor; import org.sagebionetworks.evaluation.model.SubmissionStatus; import org.sagebionetworks.evaluation.model.SubmissionStatusBatch; import org.sagebionetworks.evaluation.model.SubmissionStatusEnum; import org.sagebionetworks.evaluation.model.TeamSubmissionEligibility; import org.sagebionetworks.evaluation.model.UserEvaluationPermissions; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.ACTAccessRequirement; import org.sagebionetworks.repo.model.AccessApproval; import org.sagebionetworks.repo.model.AccessControlList; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.Challenge; import org.sagebionetworks.repo.model.ChallengePagedResults; import org.sagebionetworks.repo.model.ChallengeTeam; import org.sagebionetworks.repo.model.ChallengeTeamPagedResults; import org.sagebionetworks.repo.model.DomainType; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityBundleCreate; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityId; import org.sagebionetworks.repo.model.EntityIdList; import org.sagebionetworks.repo.model.EntityInstanceFactory; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.JoinTeamSignedToken; import org.sagebionetworks.repo.model.ListWrapper; import org.sagebionetworks.repo.model.LogEntry; import org.sagebionetworks.repo.model.MembershipInvitation; import org.sagebionetworks.repo.model.MembershipInvtnSubmission; import org.sagebionetworks.repo.model.MembershipRequest; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.PaginatedIds; import org.sagebionetworks.repo.model.ProjectHeader; import org.sagebionetworks.repo.model.ProjectListSortColumn; import org.sagebionetworks.repo.model.ProjectListType; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.ResponseMessage; import org.sagebionetworks.repo.model.RestrictableObjectDescriptor; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.model.ServiceConstants.AttachmentType; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamMember; import org.sagebionetworks.repo.model.TeamMembershipStatus; import org.sagebionetworks.repo.model.TrashedEntity; import org.sagebionetworks.repo.model.UserBundle; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupHeaderResponsePage; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.UserSessionData; import org.sagebionetworks.repo.model.VersionInfo; import org.sagebionetworks.repo.model.annotation.AnnotationsUtils; import org.sagebionetworks.repo.model.asynch.AsyncJobId; import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus; import org.sagebionetworks.repo.model.asynch.AsynchronousRequestBody; import org.sagebionetworks.repo.model.asynch.AsynchronousResponseBody; import org.sagebionetworks.repo.model.auth.ChangePasswordRequest; import org.sagebionetworks.repo.model.auth.LoginRequest; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.auth.SecretKey; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.auth.Username; import org.sagebionetworks.repo.model.dao.WikiPageKey; import org.sagebionetworks.repo.model.discussion.CreateDiscussionReply; import org.sagebionetworks.repo.model.discussion.CreateDiscussionThread; import org.sagebionetworks.repo.model.discussion.DiscussionFilter; import org.sagebionetworks.repo.model.discussion.DiscussionReplyBundle; import org.sagebionetworks.repo.model.discussion.DiscussionReplyOrder; import org.sagebionetworks.repo.model.discussion.DiscussionThreadBundle; import org.sagebionetworks.repo.model.discussion.DiscussionThreadOrder; import org.sagebionetworks.repo.model.discussion.EntityThreadCounts; import org.sagebionetworks.repo.model.discussion.Forum; import org.sagebionetworks.repo.model.discussion.MessageURL; import org.sagebionetworks.repo.model.discussion.ReplyCount; import org.sagebionetworks.repo.model.discussion.ThreadCount; import org.sagebionetworks.repo.model.discussion.UpdateReplyMessage; import org.sagebionetworks.repo.model.discussion.UpdateThreadMessage; import org.sagebionetworks.repo.model.discussion.UpdateThreadTitle; import org.sagebionetworks.repo.model.docker.DockerCommit; import org.sagebionetworks.repo.model.docker.DockerCommitSortBy; import org.sagebionetworks.repo.model.doi.Doi; import org.sagebionetworks.repo.model.entity.query.EntityQuery; import org.sagebionetworks.repo.model.entity.query.EntityQueryResults; import org.sagebionetworks.repo.model.entity.query.SortDirection; import org.sagebionetworks.repo.model.file.AddPartResponse; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyRequest; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyResult; import org.sagebionetworks.repo.model.file.BatchFileRequest; import org.sagebionetworks.repo.model.file.BatchFileResult; import org.sagebionetworks.repo.model.file.BatchPresignedUploadUrlRequest; import org.sagebionetworks.repo.model.file.BatchPresignedUploadUrlResponse; import org.sagebionetworks.repo.model.file.BulkFileDownloadRequest; import org.sagebionetworks.repo.model.file.BulkFileDownloadResponse; import org.sagebionetworks.repo.model.file.ChunkRequest; import org.sagebionetworks.repo.model.file.ChunkedFileToken; import org.sagebionetworks.repo.model.file.CompleteAllChunksRequest; import org.sagebionetworks.repo.model.file.CompleteChunkedFileRequest; import org.sagebionetworks.repo.model.file.CreateChunkedFileTokenRequest; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.FileHandleAssociation; import org.sagebionetworks.repo.model.file.FileHandleResults; import org.sagebionetworks.repo.model.file.MultipartUploadRequest; import org.sagebionetworks.repo.model.file.MultipartUploadStatus; import org.sagebionetworks.repo.model.file.ProxyFileHandle; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.S3UploadDestination; import org.sagebionetworks.repo.model.file.State; import org.sagebionetworks.repo.model.file.TempFileProviderImpl; import org.sagebionetworks.repo.model.file.UploadDaemonStatus; import org.sagebionetworks.repo.model.file.UploadDestination; import org.sagebionetworks.repo.model.file.UploadDestinationLocation; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.message.MessageBundle; import org.sagebionetworks.repo.model.message.MessageRecipientSet; import org.sagebionetworks.repo.model.message.MessageSortBy; import org.sagebionetworks.repo.model.message.MessageStatus; import org.sagebionetworks.repo.model.message.MessageStatusType; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken; import org.sagebionetworks.repo.model.oauth.OAuthProvider; import org.sagebionetworks.repo.model.oauth.OAuthUrlRequest; import org.sagebionetworks.repo.model.oauth.OAuthUrlResponse; import org.sagebionetworks.repo.model.oauth.OAuthValidationRequest; import org.sagebionetworks.repo.model.principal.AccountSetupInfo; import org.sagebionetworks.repo.model.principal.AddEmailInfo; import org.sagebionetworks.repo.model.principal.AliasCheckRequest; import org.sagebionetworks.repo.model.principal.AliasCheckResponse; import org.sagebionetworks.repo.model.principal.PrincipalAlias; import org.sagebionetworks.repo.model.principal.PrincipalAliasRequest; import org.sagebionetworks.repo.model.principal.PrincipalAliasResponse; import org.sagebionetworks.repo.model.project.ProjectSetting; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.StorageLocationSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.query.QueryTableResults; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.Quiz; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.request.ReferenceList; import org.sagebionetworks.repo.model.search.SearchResults; import org.sagebionetworks.repo.model.search.query.SearchQuery; import org.sagebionetworks.repo.model.status.StackStatus; import org.sagebionetworks.repo.model.subscription.Etag; import org.sagebionetworks.repo.model.subscription.Subscription; import org.sagebionetworks.repo.model.subscription.SubscriptionObjectType; import org.sagebionetworks.repo.model.subscription.SubscriptionPagedResults; import org.sagebionetworks.repo.model.subscription.SubscriptionRequest; import org.sagebionetworks.repo.model.subscription.Topic; import org.sagebionetworks.repo.model.table.AppendableRowSet; import org.sagebionetworks.repo.model.table.AppendableRowSetRequest; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.CsvTableDescriptor; import org.sagebionetworks.repo.model.table.DownloadFromTableRequest; import org.sagebionetworks.repo.model.table.DownloadFromTableResult; import org.sagebionetworks.repo.model.table.PaginatedColumnModels; import org.sagebionetworks.repo.model.table.Query; import org.sagebionetworks.repo.model.table.QueryBundleRequest; import org.sagebionetworks.repo.model.table.QueryNextPageToken; import org.sagebionetworks.repo.model.table.QueryResult; import org.sagebionetworks.repo.model.table.QueryResultBundle; import org.sagebionetworks.repo.model.table.RowReference; import org.sagebionetworks.repo.model.table.RowReferenceSet; import org.sagebionetworks.repo.model.table.RowReferenceSetResults; import org.sagebionetworks.repo.model.table.RowSelection; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.TableFileHandleResults; import org.sagebionetworks.repo.model.table.TableUpdateRequest; import org.sagebionetworks.repo.model.table.TableUpdateResponse; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionResponse; import org.sagebionetworks.repo.model.table.UploadToTablePreviewRequest; import org.sagebionetworks.repo.model.table.UploadToTablePreviewResult; import org.sagebionetworks.repo.model.table.UploadToTableRequest; import org.sagebionetworks.repo.model.table.UploadToTableResult; import org.sagebionetworks.repo.model.table.ViewType; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot; import org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.verification.VerificationPagedResults; import org.sagebionetworks.repo.model.verification.VerificationState; import org.sagebionetworks.repo.model.verification.VerificationStateEnum; import org.sagebionetworks.repo.model.verification.VerificationSubmission; import org.sagebionetworks.repo.model.versionInfo.SynapseVersionInfo; import org.sagebionetworks.repo.model.wiki.WikiHeader; import org.sagebionetworks.repo.model.wiki.WikiPage; import org.sagebionetworks.repo.model.wiki.WikiVersionsList; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.schema.adapter.JSONEntity; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl; import org.sagebionetworks.util.ValidateArgument; import org.sagebionetworks.utils.MD5ChecksumHelper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; /** * Low-level Java Client API for Synapse REST APIs */ public class SynapseClientImpl extends BaseClientImpl implements SynapseClient { public static final String SYNPASE_JAVA_CLIENT = "Synpase-Java-Client/"; public static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; private static final Logger log = LogManager .getLogger(SynapseClientImpl.class.getName()); private static final long MAX_UPLOAD_DAEMON_MS = 60 * 1000; private static final String DEFAULT_REPO_ENDPOINT = "https://repo-prod.prod.sagebase.org/repo/v1"; private static final String DEFAULT_AUTH_ENDPOINT = SharedClientConnection.DEFAULT_AUTH_ENDPOINT; private static final String DEFAULT_FILE_ENDPOINT = "https://repo-prod.prod.sagebase.org/file/v1"; private static final String ACCOUNT = "/account"; private static final String EMAIL_VALIDATION = "/emailValidation"; private static final String ACCOUNT_EMAIL_VALIDATION = ACCOUNT + EMAIL_VALIDATION; private static final String EMAIL = "/email"; private static final String PORTAL_ENDPOINT_PARAM = "portalEndpoint"; private static final String SET_AS_NOTIFICATION_EMAIL_PARAM = "setAsNotificationEmail"; private static final String EMAIL_PARAM = "email"; private static final String PARAM_GENERATED_BY = "generatedBy"; private static final String QUERY = "/query"; private static final String QUERY_URI = QUERY + "?query="; private static final String REPO_SUFFIX_VERSION = "/version"; private static final String ANNOTATION_URI_SUFFIX = "annotations"; protected static final String ADMIN = "/admin"; protected static final String STACK_STATUS = ADMIN + "/synapse/status"; private static final String ENTITY = "/entity"; private static final String GENERATED_BY_SUFFIX = "/generatedBy"; private static final String ENTITY_URI_PATH = "/entity"; private static final String ENTITY_ACL_PATH_SUFFIX = "/acl"; private static final String ENTITY_ACL_RECURSIVE_SUFFIX = "?recursive=true"; private static final String ENTITY_BUNDLE_PATH = "/bundle?mask="; private static final String BUNDLE = "/bundle"; private static final String BENEFACTOR = "/benefactor"; // from // org.sagebionetworks.repo.web.UrlHelpers private static final String ACTIVITY_URI_PATH = "/activity"; private static final String GENERATED_PATH = "/generated"; private static final String FAVORITE_URI_PATH = "/favorite"; private static final String PROJECTS_URI_PATH = "/projects"; public static final String PRINCIPAL = "/principal"; public static final String PRINCIPAL_AVAILABLE = PRINCIPAL + "/available"; public static final String NOTIFICATION_EMAIL = "/notificationEmail"; private static final String WIKI_URI_TEMPLATE = "/%1$s/%2$s/wiki"; private static final String WIKI_ID_URI_TEMPLATE = "/%1$s/%2$s/wiki/%3$s"; private static final String WIKI_TREE_URI_TEMPLATE = "/%1$s/%2$s/wikiheadertree"; private static final String WIKI_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2"; private static final String WIKI_ID_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2/%3$s"; private static final String WIKI_ID_VERSION_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2/%3$s/%4$s"; private static final String WIKI_TREE_URI_TEMPLATE_V2 = "/%1$s/%2$s/wikiheadertree2"; private static final String WIKI_ORDER_HINT_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2orderhint"; private static final String WIKI_HISTORY_V2 = "/wikihistory"; private static final String ATTACHMENT_HANDLES = "/attachmenthandles"; private static final String ATTACHMENT_FILE = "/attachment"; private static final String MARKDOWN_FILE = "/markdown"; private static final String ATTACHMENT_FILE_PREVIEW = "/attachmentpreview"; private static final String FILE_NAME_PARAMETER = "?fileName="; private static final String REDIRECT_PARAMETER = "redirect="; private static final String OFFSET_PARAMETER = "offset="; private static final String LIMIT_PARAMETER = "limit="; private static final String VERSION_PARAMETER = "?wikiVersion="; private static final String AND_VERSION_PARAMETER = "&wikiVersion="; private static final String AND_LIMIT_PARAMETER = "&" + LIMIT_PARAMETER; private static final String AND_REDIRECT_PARAMETER = "&" + REDIRECT_PARAMETER; private static final String QUERY_REDIRECT_PARAMETER = "?" + REDIRECT_PARAMETER; private static final String ACCESS_TYPE_PARAMETER = "accessType"; private static final String EVALUATION_URI_PATH = "/evaluation"; private static final String AVAILABLE_EVALUATION_URI_PATH = "/evaluation/available"; private static final String NAME = "name"; private static final String ALL = "/all"; private static final String STATUS = "/status"; private static final String STATUS_BATCH = "/statusBatch"; private static final String LOCK_ACCESS_REQUIREMENT = "/lockAccessRequirement"; private static final String SUBMISSION = "submission"; private static final String SUBMISSION_BUNDLE = SUBMISSION + BUNDLE; private static final String SUBMISSION_ALL = SUBMISSION + ALL; private static final String SUBMISSION_STATUS_ALL = SUBMISSION + STATUS + ALL; private static final String SUBMISSION_BUNDLE_ALL = SUBMISSION + BUNDLE + ALL; private static final String STATUS_SUFFIX = "?status="; private static final String EVALUATION_ACL_URI_PATH = "/evaluation/acl"; private static final String EVALUATION_QUERY_URI_PATH = EVALUATION_URI_PATH + "/" + SUBMISSION + QUERY_URI; private static final String EVALUATION_IDS_FILTER_PARAM = "evaluationIds"; private static final String SUBMISSION_ELIGIBILITY = "/submissionEligibility"; private static final String SUBMISSION_ELIGIBILITY_HASH = "submissionEligibilityHash"; private static final String MESSAGE = "/message"; private static final String FORWARD = "/forward"; private static final String CONVERSATION = "/conversation"; private static final String MESSAGE_STATUS = MESSAGE + "/status"; private static final String MESSAGE_INBOX = MESSAGE + "/inbox"; private static final String MESSAGE_OUTBOX = MESSAGE + "/outbox"; private static final String MESSAGE_INBOX_FILTER_PARAM = "inboxFilter"; private static final String MESSAGE_ORDER_BY_PARAM = "orderBy"; private static final String MESSAGE_DESCENDING_PARAM = "descending"; protected static final String ASYNC_START = "/async/start"; protected static final String ASYNC_GET = "/async/get/"; protected static final String COLUMN = "/column"; protected static final String COLUMN_BATCH = COLUMN + "/batch"; protected static final String COLUMN_VIEW_DEFAULT = COLUMN + "/tableview/defaults/"; protected static final String TABLE = "/table"; protected static final String ROW_ID = "/row"; protected static final String ROW_VERSION = "/version"; protected static final String TABLE_QUERY = TABLE + "/query"; protected static final String TABLE_QUERY_NEXTPAGE = TABLE_QUERY + "/nextPage"; protected static final String TABLE_DOWNLOAD_CSV = TABLE + "/download/csv"; protected static final String TABLE_UPLOAD_CSV = TABLE + "/upload/csv"; protected static final String TABLE_UPLOAD_CSV_PREVIEW = TABLE + "/upload/csv/preview"; protected static final String TABLE_APPEND = TABLE + "/append"; protected static final String TABLE_TRANSACTION = TABLE+"/transaction"; protected static final String ASYNCHRONOUS_JOB = "/asynchronous/job"; private static final String USER_PROFILE_PATH = "/userProfile"; private static final String NOTIFICATION_SETTINGS = "/notificationSettings"; private static final String PROFILE_IMAGE = "/image"; private static final String PROFILE_IMAGE_PREVIEW = PROFILE_IMAGE+"/preview"; private static final String USER_GROUP_HEADER_BATCH_PATH = "/userGroupHeaders/batch?ids="; private static final String USER_GROUP_HEADER_PREFIX_PATH = "/userGroupHeaders?prefix="; private static final String TOTAL_NUM_RESULTS = "totalNumberOfResults"; private static final String ACCESS_REQUIREMENT = "/accessRequirement"; private static final String ACCESS_REQUIREMENT_UNFULFILLED = "/accessRequirementUnfulfilled"; private static final String ACCESS_APPROVAL = "/accessApproval"; private static final String VERSION_INFO = "/version"; private static final String FILE_HANDLE = "/fileHandle"; private static final String FILE = "/file"; private static final String FILE_PREVIEW = "/filepreview"; private static final String EXTERNAL_FILE_HANDLE = "/externalFileHandle"; private static final String EXTERNAL_FILE_HANDLE_S3 = "/externalFileHandle/s3"; private static final String EXTERNAL_FILE_HANDLE_PROXY = "/externalFileHandle/proxy"; private static final String FILE_HANDLES = "/filehandles"; protected static final String S3_FILE_COPY = FILE + "/s3FileCopy"; private static final String FILE_HANDLES_COPY = FILE_HANDLES+"/copy"; protected static final String FILE_BULK = FILE+"/bulk"; private static final String CREATE_CHUNKED_FILE_UPLOAD_TOKEN = "/createChunkedFileUploadToken"; private static final String CREATE_CHUNKED_FILE_UPLOAD_CHUNK_URL = "/createChunkedFileUploadChunkURL"; private static final String START_COMPLETE_UPLOAD_DAEMON = "/startCompleteUploadDaemon"; private static final String COMPLETE_UPLOAD_DAEMON_STATUS = "/completeUploadDaemonStatus"; private static final String TRASHCAN_TRASH = "/trashcan/trash"; private static final String TRASHCAN_RESTORE = "/trashcan/restore"; private static final String TRASHCAN_VIEW = "/trashcan/view"; private static final String TRASHCAN_PURGE = "/trashcan/purge"; private static final String CHALLENGE = "/challenge"; private static final String REGISTRATABLE_TEAM = "/registratableTeam"; private static final String CHALLENGE_TEAM = "/challengeTeam"; private static final String SUBMISSION_TEAMS = "/submissionTeams"; private static final String LOG = "/log"; private static final String DOI = "/doi"; private static final String ETAG = "etag"; private static final String PROJECT_SETTINGS = "/projectSettings"; private static final String STORAGE_LOCATION = "/storageLocation"; public static final String AUTH_OAUTH_2 = "/oauth2"; public static final String AUTH_OAUTH_2_AUTH_URL = AUTH_OAUTH_2+"/authurl"; public static final String AUTH_OAUTH_2_SESSION = AUTH_OAUTH_2+"/session"; public static final String AUTH_OAUTH_2_ALIAS = AUTH_OAUTH_2+"/alias"; private static final String VERIFICATION_SUBMISSION = "/verificationSubmission"; private static final String CURRENT_VERIFICATION_STATE = "currentVerificationState"; private static final String VERIFICATION_STATE = "/state"; private static final String VERIFIED_USER_ID = "verifiedUserId"; private static final String USER_BUNDLE = "/bundle"; private static final String FILE_ASSOCIATE_TYPE = "fileAssociateType"; private static final String FILE_ASSOCIATE_ID = "fileAssociateId"; public static final String FILE_HANDLE_BATCH = "/fileHandle/batch"; // web request pagination parameters public static final String LIMIT = "limit"; public static final String OFFSET = "offset"; private static final long MAX_BACKOFF_MILLIS = 5 * 60 * 1000L; // five // minutes /** * The character encoding to use with strings which are the body of email * messages */ private static final Charset MESSAGE_CHARSET = Charset.forName("UTF-8"); private static final String LIMIT_1_OFFSET_1 = "' limit 1 offset 1"; private static final String SELECT_ID_FROM_ENTITY_WHERE_PARENT_ID = "select id from entity where parentId == '"; // Team protected static final String TEAM = "/team"; protected static final String TEAMS = "/teams"; private static final String TEAM_LIST = "/teamList"; private static final String MEMBER_LIST = "/memberList"; protected static final String USER = "/user"; protected static final String NAME_FRAGMENT_FILTER = "fragment"; protected static final String ICON = "/icon"; protected static final String TEAM_MEMBERS = "/teamMembers"; protected static final String MEMBER = "/member"; protected static final String PERMISSION = "/permission"; protected static final String MEMBERSHIP_STATUS = "/membershipStatus"; protected static final String TEAM_MEMBERSHIP_PERMISSION = "isAdmin"; // membership invitation private static final String MEMBERSHIP_INVITATION = "/membershipInvitation"; private static final String OPEN_MEMBERSHIP_INVITATION = "/openInvitation"; private static final String TEAM_ID_REQUEST_PARAMETER = "teamId"; private static final String INVITEE_ID_REQUEST_PARAMETER = "inviteeId"; // membership request private static final String MEMBERSHIP_REQUEST = "/membershipRequest"; private static final String OPEN_MEMBERSHIP_REQUEST = "/openRequest"; private static final String REQUESTOR_ID_REQUEST_PARAMETER = "requestorId"; public static final String ACCEPT_INVITATION_ENDPOINT_PARAM = "acceptInvitationEndpoint"; public static final String ACCEPT_REQUEST_ENDPOINT_PARAM = "acceptRequestEndpoint"; public static final String NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM = "notificationUnsubscribeEndpoint"; public static final String TEAM_ENDPOINT_PARAM = "teamEndpoint"; public static final String CHALLENGE_ENDPOINT_PARAM = "challengeEndpoint"; private static final String CERTIFIED_USER_TEST = "/certifiedUserTest"; private static final String CERTIFIED_USER_TEST_RESPONSE = "/certifiedUserTestResponse"; private static final String CERTIFIED_USER_PASSING_RECORD = "/certifiedUserPassingRecord"; private static final String CERTIFIED_USER_PASSING_RECORDS = "/certifiedUserPassingRecords"; private static final String CERTIFIED_USER_STATUS = "/certificationStatus"; private static final String PROJECT = "/project"; private static final String FORUM = "/forum"; private static final String THREAD = "/thread"; private static final String THREADS = "/threads"; private static final String THREAD_COUNT = "/threadcount"; private static final String THREAD_TITLE = "/title"; private static final String DISCUSSION_MESSAGE = "/message"; private static final String REPLY = "/reply"; private static final String REPLIES = "/replies"; private static final String REPLY_COUNT = "/replycount"; private static final String URL = "/messageUrl"; private static final String PIN = "/pin"; private static final String UNPIN = "/unpin"; private static final String RESTORE = "/restore"; private static final String MODERATORS = "/moderators"; private static final String THREAD_COUNTS = "/threadcounts"; private static final String ENTITY_THREAD_COUNTS = ENTITY + THREAD_COUNTS; private static final String SUBSCRIPTION = "/subscription"; private static final String LIST = "/list"; private static final String OBJECT_TYPE_PARAM = "objectType"; private static final String OBJECT = "/object"; private static final String PRINCIPAL_ID_REQUEST_PARAM = "principalId"; private static final String DOCKER_COMMIT = "/dockerCommit"; protected String repoEndpoint; protected String authEndpoint; protected String fileEndpoint; /** * The maximum number of threads that should be used to upload asynchronous * file chunks. */ private static final int MAX_NUMBER_OF_THREADS = 2; /** * This thread pool is used for asynchronous file chunk uploads. */ private ExecutorService fileUplaodthreadPool = Executors .newFixedThreadPool(MAX_NUMBER_OF_THREADS); /** * Note: 5 MB is currently the minimum size of a single part of S3 * Multi-part upload, so any file chunk must be at least this size. */ public static final int MINIMUM_CHUNK_SIZE_BYTES = ((int) Math.pow(2, 20)) * 5; /** * Default constructor uses the default repository and auth services * endpoints. */ public SynapseClientImpl() { // Use the default implementations this(new SharedClientConnection(new HttpClientProviderImpl())); } /** * Will use the same connection as the other client * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(BaseClient other) { this(other.getSharedClientConnection()); } /** * Will use the shared connection provider and data uploader. * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(SharedClientConnection sharedClientConnection) { super(SYNPASE_JAVA_CLIENT + ClientVersionInfo.getClientVersionInfo(), sharedClientConnection); if (sharedClientConnection == null) throw new IllegalArgumentException( "SharedClientConnection cannot be null"); setRepositoryEndpoint(DEFAULT_REPO_ENDPOINT); setAuthEndpoint(DEFAULT_AUTH_ENDPOINT); setFileEndpoint(DEFAULT_FILE_ENDPOINT); } /** * Default constructor uses the default repository and auth services * endpoints. */ public SynapseClientImpl(DomainType domain) { // Use the default implementations this(new HttpClientProviderImpl(), domain); } /** * Will use the provided client provider and data uploader. * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(HttpClientProvider clientProvider, DomainType domain) { this(new SharedClientConnection(clientProvider, domain)); } /** * Use this method to override the default implementation of * {@link HttpClientProvider} * * @param clientProvider */ public void setHttpClientProvider(HttpClientProvider clientProvider) { getSharedClientConnection().setHttpClientProvider(clientProvider); } /** * Returns a helper class for making specialized Http requests * */ private HttpClientHelper getHttpClientHelper() { return new HttpClientHelper(getSharedClientConnection().getHttpClientProvider()); } /** * @param repoEndpoint * the repoEndpoint to set */ @Override public void setRepositoryEndpoint(String repoEndpoint) { this.repoEndpoint = repoEndpoint; } /** * Get the configured Repository Service Endpoint * * @return */ @Override public String getRepoEndpoint() { return repoEndpoint; } /** * @param authEndpoint * the authEndpoint to set */ @Override public void setAuthEndpoint(String authEndpoint) { this.authEndpoint = authEndpoint; getSharedClientConnection().setAuthEndpoint(authEndpoint); } /** * Get the configured Authorization Service Endpoint * * @return */ @Override public String getAuthEndpoint() { return authEndpoint; } /** * @param fileEndpoint * the authEndpoint to set */ @Override public void setFileEndpoint(String fileEndpoint) { this.fileEndpoint = fileEndpoint; } /** * The endpoint used for file multi-part upload. * * @return */ @Override public String getFileEndpoint() { return this.fileEndpoint; } /** * Lookup the endpoint for a given type. * @param type * @return */ String getEndpointForType(RestEndpointType type){ switch(type){ case auth: return getAuthEndpoint(); case repo: return getRepoEndpoint(); case file: return getFileEndpoint(); default: throw new IllegalArgumentException("Unknown type: "+type); } } /** * @param request */ @Override public void setRequestProfile(boolean request) { getSharedClientConnection().setRequestProfile(request); } /** * @return JSONObject */ @Override public JSONObject getProfileData() { return getSharedClientConnection().getProfileData(); } /** * @return the userName */ @Override public String getUserName() { return getSharedClientConnection().getUserName(); } /** * @param userName * the userName to set */ @Override public void setUserName(String userName) { getSharedClientConnection().setUserName(userName); } /** * @return the apiKey */ @Override public String getApiKey() { return getSharedClientConnection().getApiKey(); } /** * @param apiKey * the apiKey to set */ @Override public void setApiKey(String apiKey) { getSharedClientConnection().setApiKey(apiKey); } @Deprecated @Override public Session login(String username, String password) throws SynapseException { return getSharedClientConnection().login(username, password, getUserAgent()); } @Override public LoginResponse login(LoginRequest request) throws SynapseException { return getSharedClientConnection().login(request, getUserAgent()); } @Override public void logout() throws SynapseException { getSharedClientConnection().logout(getUserAgent()); } @Override public UserSessionData getUserSessionData() throws SynapseException { Session session = new Session(); session.setSessionToken(getCurrentSessionToken()); try { revalidateSession(); session.setAcceptsTermsOfUse(true); } catch (SynapseTermsOfUseException e) { session.setAcceptsTermsOfUse(false); } UserSessionData userData = null; userData = new UserSessionData(); userData.setSession(session); if (session.getAcceptsTermsOfUse()) { userData.setProfile(getMyProfile()); } return userData; } @Override public boolean revalidateSession() throws SynapseException { return getSharedClientConnection().revalidateSession(getUserAgent()); } /******************** * Mid Level Repository Service APIs * * @throws SynapseException ********************/ @Override public AliasCheckResponse checkAliasAvailable(AliasCheckRequest request) throws SynapseException { String url = PRINCIPAL_AVAILABLE; return asymmetricalPost(getRepoEndpoint(), url, request, AliasCheckResponse.class, null); } /** * Send an email validation message as a precursor to creating a new user * account. * * @param user * the first name, last name and email address for the new user * @param portalEndpoint * the GUI endpoint (is the basis for the link in the email * message) Must generate a valid email when a set of request * parameters is appended to the end. */ @Override public void newAccountEmailValidation(NewUser user, String portalEndpoint) throws SynapseException { if (user == null) throw new IllegalArgumentException("email can not be null."); if (portalEndpoint == null) throw new IllegalArgumentException( "portalEndpoint can not be null."); String uri = ACCOUNT_EMAIL_VALIDATION; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(PORTAL_ENDPOINT_PARAM, portalEndpoint); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(user.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Create a new account, following email validation. Sets the password and * logs the user in, returning a valid session token * * @param accountSetupInfo * Note: Caller may override the first/last name, but not the * email, given in 'newAccountEmailValidation' * @return session * @throws NotFoundException */ @Override public Session createNewAccount(AccountSetupInfo accountSetupInfo) throws SynapseException { if (accountSetupInfo == null) throw new IllegalArgumentException( "accountSetupInfo can not be null."); String uri = ACCOUNT; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(accountSetupInfo.writeToJSONObject( toUpdateAdapter).toJSONString()); JSONObject result = getSharedClientConnection().postJson( repoEndpoint, uri, obj.toString(), getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(result, Session.class); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Send an email validation as a precursor to adding a new email address to * an existing account. * * @param email * the email which is claimed by the user * @param portalEndpoint * the GUI endpoint (is the basis for the link in the email * message) Must generate a valid email when a set of request * parameters is appended to the end. * @throws NotFoundException */ @Override public void additionalEmailValidation(Long userId, String email, String portalEndpoint) throws SynapseException { if (userId == null) throw new IllegalArgumentException("userId can not be null."); if (email == null) throw new IllegalArgumentException("email can not be null."); if (portalEndpoint == null) throw new IllegalArgumentException( "portalEndpoint can not be null."); String uri = ACCOUNT + "/" + userId + EMAIL_VALIDATION; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(PORTAL_ENDPOINT_PARAM, portalEndpoint); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { Username emailRequestBody = new Username(); emailRequestBody.setEmail(email); JSONObject obj = new JSONObject(emailRequestBody.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Add a new email address to an existing account. * * @param addEmailInfo * the token sent to the user via email * @param setAsNotificationEmail * if true then set the new email address to be the user's * notification address * @throws NotFoundException */ @Override public void addEmail(AddEmailInfo addEmailInfo, Boolean setAsNotificationEmail) throws SynapseException { if (addEmailInfo == null) throw new IllegalArgumentException("addEmailInfo can not be null."); String uri = EMAIL; Map<String, String> paramMap = new HashMap<String, String>(); if (setAsNotificationEmail != null) paramMap.put(SET_AS_NOTIFICATION_EMAIL_PARAM, setAsNotificationEmail.toString()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(addEmailInfo.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Remove an email address from an existing account. * * @param email * the email to remove. Must be an established email address for * the user * @throws NotFoundException */ @Override public void removeEmail(String email) throws SynapseException { if (email == null) throw new IllegalArgumentException("email can not be null."); String uri = EMAIL; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(EMAIL_PARAM, email); getSharedClientConnection().deleteUri(repoEndpoint, uri, getUserAgent(), paramMap); } /** * This sets the email used for user notifications, i.e. when a Synapse * message is sent and if the user has elected to receive messages by email, * then this is the email address at which the user will receive the * message. Note: The given email address must already be established as * being owned by the user. */ public void setNotificationEmail(String email) throws SynapseException { if (email == null) { throw new IllegalArgumentException("email can not be null."); } String url = NOTIFICATION_EMAIL; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { Username un = new Username(); un.setEmail(email); obj = new JSONObject(un.writeToJSONObject(toUpdateAdapter) .toJSONString()); getSharedClientConnection().putJson(repoEndpoint, url, obj.toString(), getUserAgent()); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * This gets the email used for user notifications, i.e. when a Synapse * message is sent and if the user has elected to receive messages by email, * then this is the email address at which the user will receive the * message. * * @throws SynapseException */ public String getNotificationEmail() throws SynapseException { String url = NOTIFICATION_EMAIL; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { Username un = new Username(); un.initializeFromJSONObject(adapter); return un.getEmail(); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Create a new dataset, layer, etc ... * * @param uri * @param entity * @return the newly created entity * @throws SynapseException */ @Override public JSONObject createJSONObject(String uri, JSONObject entity) throws SynapseException { return getSharedClientConnection().postJson(repoEndpoint, uri, entity.toString(), getUserAgent(), null); } /** * Create a new Entity. * * @param <T> * @param entity * @return the newly created entity * @throws SynapseException */ @Override public <T extends Entity> T createEntity(T entity) throws SynapseException { return createEntity(entity, null); } /** * Create a new Entity. * * @param <T> * @param entity * @param activityId * set generatedBy relationship to the new entity * @return the newly created entity * @throws SynapseException */ @Override public <T extends Entity> T createEntity(T entity, String activityId) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); entity.setConcreteType(entity.getClass().getName()); String uri = ENTITY_URI_PATH; if (activityId != null) uri += "?" + PARAM_GENERATED_BY + "=" + activityId; return createJSONEntity(uri, entity); } /** * Create a new Entity. * * @param <T> * @param entity * @return the newly created entity * @throws SynapseException */ @Override @SuppressWarnings("unchecked") public <T extends JSONEntity> T createJSONEntity(String uri, T entity) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(entity); // Create the entity jsonObject = createJSONObject(uri, jsonObject); // Now convert to Object to an entity return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public <T extends JSONEntity> List<T> createJSONEntityFromListWrapper(String uri, ListWrapper<T> entity, Class<T> elementType) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); try { String jsonString = EntityFactory.createJSONStringForEntity(entity); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), uri, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), elementType); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Create an Entity, Annotations, and ACL with a single call. * * @param ebc * @return * @throws SynapseException */ @Override public EntityBundle createEntityBundle(EntityBundleCreate ebc) throws SynapseException { return createEntityBundle(ebc, null); } /** * Create an Entity, Annotations, and ACL with a single call. * * @param ebc * @param activityId * the activity to create a generatedBy relationship with the * entity in the Bundle. * @return * @throws SynapseException */ @Override public EntityBundle createEntityBundle(EntityBundleCreate ebc, String activityId) throws SynapseException { if (ebc == null) throw new IllegalArgumentException("EntityBundle cannot be null"); String url = ENTITY_URI_PATH + BUNDLE; JSONObject jsonObject; if (activityId != null) url += "?" + PARAM_GENERATED_BY + "=" + activityId; try { // Convert to JSON jsonObject = EntityFactory.createJSONObjectForEntity(ebc); // Create jsonObject = createJSONObject(url, jsonObject); // Convert returned JSON to EntityBundle return EntityFactory.createEntityFromJSONObject(jsonObject, EntityBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Update an Entity, Annotations, and ACL with a single call. * * @param ebc * @return * @throws SynapseException */ @Override public EntityBundle updateEntityBundle(String entityId, EntityBundleCreate ebc) throws SynapseException { return updateEntityBundle(entityId, ebc, null); } /** * Update an Entity, Annotations, and ACL with a single call. * * @param ebc * @param activityId * the activity to create a generatedBy relationship with the * entity in the Bundle. * @return * @throws SynapseException */ @Override public EntityBundle updateEntityBundle(String entityId, EntityBundleCreate ebc, String activityId) throws SynapseException { if (ebc == null) throw new IllegalArgumentException("EntityBundle cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + BUNDLE; JSONObject jsonObject; try { // Convert to JSON jsonObject = EntityFactory.createJSONObjectForEntity(ebc); // Update. Bundles do not have their own etags, so we use an // empty requestHeaders object. jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); // Convert returned JSON to EntityBundle return EntityFactory.createEntityFromJSONObject(jsonObject, EntityBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get an entity using its ID. * * @param entityId * @return the entity * @throws SynapseException */ @Override public Entity getEntityById(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); return getEntityByIdForVersion(entityId, null); } /** * Get a specific version of an entity using its ID an version number. * * @param entityId * @param versionNumber * @return the entity * @throws SynapseException */ @Override public Entity getEntityByIdForVersion(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId; if (versionNumber != null) { url += REPO_SUFFIX_VERSION + "/" + versionNumber; } JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); // Get the type from the object if (!adapter.has("entityType")) throw new RuntimeException("EntityType returned was null!"); try { String entityType = adapter.getString("entityType"); Entity entity = (Entity) EntityInstanceFactory.singleton().newInstance(entityType); entity.initializeFromJSONObject(adapter); return entity; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get a bundle of information about an entity in a single call. * * @param entityId * @param partsMask * @return * @throws SynapseException */ @Override public EntityBundle getEntityBundle(String entityId, int partsMask) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + ENTITY_BUNDLE_PATH + partsMask; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { EntityBundle eb = new EntityBundle(); eb.initializeFromJSONObject(adapter); return eb; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get a bundle of information about an entity in a single call. * * @param entityId * - the entity id to retrieve * @param versionNumber * - the specific version to retrieve * @param partsMask * @return * @throws SynapseException */ @Override public EntityBundle getEntityBundle(String entityId, Long versionNumber, int partsMask) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (versionNumber == null) throw new IllegalArgumentException("versionNumber cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + REPO_SUFFIX_VERSION + "/" + versionNumber + ENTITY_BUNDLE_PATH + partsMask; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { EntityBundle eb = new EntityBundle(); eb.initializeFromJSONObject(adapter); return eb; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * * @param entityId * @return * @throws SynapseException */ @Override public PaginatedResults<VersionInfo> getEntityVersions(String entityId, int offset, int limit) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + REPO_SUFFIX_VERSION + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<VersionInfo> results = new PaginatedResults<VersionInfo>( VersionInfo.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public static <T extends JSONEntity> T initializeFromJSONObject( JSONObject o, Class<T> clazz) throws SynapseException { try { T obj = clazz.newInstance(); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(o); Iterator<String> it = adapter.keys(); while (it.hasNext()) { String s = it.next(); log.trace(s); } obj.initializeFromJSONObject(adapter); return obj; } catch (IllegalAccessException e) { throw new SynapseClientException(e); } catch (InstantiationException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getACL(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, AccessControlList.class); } @Override public EntityHeader getEntityBenefactor(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + BENEFACTOR; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, EntityHeader.class); } @Override public UserProfile getMyProfile() throws SynapseException { String uri = USER_PROFILE_PATH; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserProfile.class); } @Override public void updateMyProfile(UserProfile userProfile) throws SynapseException { try { String uri = USER_PROFILE_PATH; getSharedClientConnection().putJson( repoEndpoint, uri, EntityFactory.createJSONObjectForEntity(userProfile) .toString(), getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ResponseMessage updateNotificationSettings(NotificationSettingsSignedToken token) throws SynapseException { return asymmetricalPut(getRepoEndpoint(), NOTIFICATION_SETTINGS, token, ResponseMessage.class); } @Override public UserProfile getUserProfile(String ownerId) throws SynapseException { String uri = USER_PROFILE_PATH + "/" + ownerId; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserProfile.class); } /** * Batch get headers for users/groups matching a list of Synapse IDs. * * @param ids * @return * @throws JSONException * @throws SynapseException */ @Override public UserGroupHeaderResponsePage getUserGroupHeadersByIds(List<String> ids) throws SynapseException { String uri = listToString(ids); JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getUserProfilePictureUrl(java.lang.String) */ @Override public URL getUserProfilePictureUrl(String ownerId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = USER_PROFILE_PATH+"/"+ownerId+PROFILE_IMAGE+"?"+REDIRECT_PARAMETER+"false"; return getUrl(url); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getUserProfilePicturePreviewUrl(java.lang.String) */ @Override public URL getUserProfilePicturePreviewUrl(String ownerId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = USER_PROFILE_PATH+"/"+ownerId+PROFILE_IMAGE_PREVIEW+"?"+REDIRECT_PARAMETER+"false"; return getUrl(url); } private String listToString(List<String> ids) { StringBuilder sb = new StringBuilder(); sb.append(USER_GROUP_HEADER_BATCH_PATH); for (String id : ids) { sb.append(id); sb.append(','); } // Remove the trailing comma sb.deleteCharAt(sb.length() - 1); return sb.toString(); } @Override public UserGroupHeaderResponsePage getUserGroupHeadersByPrefix(String prefix) throws SynapseException, UnsupportedEncodingException { String encodedPrefix = URLEncoder.encode(prefix, "UTF-8"); JSONObject json = getEntity(USER_GROUP_HEADER_PREFIX_PATH + encodedPrefix); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } @Override public UserGroupHeaderResponsePage getUserGroupHeadersByPrefix( String prefix, long limit, long offset) throws SynapseException, UnsupportedEncodingException { String encodedPrefix = URLEncoder.encode(prefix, "UTF-8"); JSONObject json = getEntity(USER_GROUP_HEADER_PREFIX_PATH + encodedPrefix + "&" + LIMIT_PARAMETER + limit + "&" + OFFSET_PARAMETER + offset); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } /** * Update an ACL. Default to non-recursive application. */ @Override public AccessControlList updateACL(AccessControlList acl) throws SynapseException { return updateACL(acl, false); } /** * Update an entity's ACL. If 'recursive' is set to true, then any child * ACLs will be deleted, such that all child entities inherit this ACL. */ @Override public AccessControlList updateACL(AccessControlList acl, boolean recursive) throws SynapseException { String entityId = acl.getId(); String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; if (recursive) uri += ENTITY_ACL_RECURSIVE_SUFFIX; try { JSONObject jsonAcl = EntityFactory.createJSONObjectForEntity(acl); jsonAcl = getSharedClientConnection().putJson(repoEndpoint, uri, jsonAcl.toString(), getUserAgent()); return initializeFromJSONObject(jsonAcl, AccessControlList.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteACL(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public AccessControlList createACL(AccessControlList acl) throws SynapseException { String entityId = acl.getId(); String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; try { JSONObject jsonAcl = EntityFactory.createJSONObjectForEntity(acl); jsonAcl = createJSONObject(uri, jsonAcl); return initializeFromJSONObject(jsonAcl, AccessControlList.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<UserProfile> getUsers(int offset, int limit) throws SynapseException { String uri = "/user?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonUsers = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonUsers); PaginatedResults<UserProfile> results = new PaginatedResults<UserProfile>( UserProfile.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<UserProfile> listUserProfiles(List<Long> userIds) throws SynapseException { try { IdList idList = new IdList(); idList.setList(userIds); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), USER_PROFILE_PATH, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), UserProfile.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<UserGroup> getGroups(int offset, int limit) throws SynapseException { String uri = "/userGroup?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonUsers = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonUsers); PaginatedResults<UserGroup> results = new PaginatedResults<UserGroup>( UserGroup.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the current user's permission for a given entity. * * @param entityId * @return * @throws SynapseException */ @Override public UserEntityPermissions getUsersEntityPermissions(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/permissions"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserEntityPermissions uep = new UserEntityPermissions(); try { uep.initializeFromJSONObject(adapter); return uep; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the current user's permission for a given entity. * * @param entityId * @return * @throws SynapseException */ @Override public boolean canAccess(String entityId, ACCESS_TYPE accessType) throws SynapseException { return canAccess(entityId, ObjectType.ENTITY, accessType); } @Override public boolean canAccess(String id, ObjectType type, ACCESS_TYPE accessType) throws SynapseException { if (id == null) throw new IllegalArgumentException("id cannot be null"); if (type == null) throw new IllegalArgumentException("ObjectType cannot be null"); if (accessType == null) throw new IllegalArgumentException("AccessType cannot be null"); if (ObjectType.ENTITY.equals(type)) { return canAccess(ENTITY_URI_PATH + "/" + id + "/access?accessType=" + accessType.name()); } else if (ObjectType.EVALUATION.equals(type)) { return canAccess(EVALUATION_URI_PATH + "/" + id + "/access?accessType=" + accessType.name()); } else throw new IllegalArgumentException("ObjectType not supported: " + type.toString()); } private boolean canAccess(String serviceUrl) throws SynapseException { try { JSONObject jsonObj = getEntity(serviceUrl); String resultString = null; try { resultString = jsonObj.getString("result"); } catch (NullPointerException e) { throw new SynapseClientException(jsonObj.toString(), e); } return Boolean.parseBoolean(resultString); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Get the annotations for an entity. * * @param entityId * @return * @throws SynapseException */ @Override public Annotations getAnnotations(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/annotations"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Annotations annos = new Annotations(); try { annos.initializeFromJSONObject(adapter); return annos; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } /** * Update the annotations of an entity. * * @param entityId * @return * @throws SynapseException */ @Override public Annotations updateAnnotations(String entityId, Annotations updated) throws SynapseException { try { String url = ENTITY_URI_PATH + "/" + entityId + "/annotations"; JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(updated); // Update jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); // Parse the results JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); Annotations annos = new Annotations(); annos.initializeFromJSONObject(adapter); return annos; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @SuppressWarnings("unchecked") private static Class<AccessRequirement> getAccessRequirementClassFromType( String s) { try { return (Class<AccessRequirement>) Class.forName(s); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessRequirement> T createAccessRequirement(T ar) throws SynapseException { if (ar == null) throw new IllegalArgumentException( "AccessRequirement cannot be null"); ar.setConcreteType(ar.getClass().getName()); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(ar); // Create the entity jsonObject = createJSONObject(ACCESS_REQUIREMENT, jsonObject); // Now convert to Object to an entity return (T) initializeFromJSONObject(jsonObject, getAccessRequirementClassFromType(ar.getConcreteType())); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessRequirement> T updateAccessRequirement(T ar) throws SynapseException { if (ar == null) throw new IllegalArgumentException( "AccessRequirement cannot be null"); String url = createEntityUri(ACCESS_REQUIREMENT + "/", ar.getId() .toString()); try { JSONObject toUpdateJsonObject = EntityFactory .createJSONObjectForEntity(ar); JSONObject updatedJsonObject = getSharedClientConnection().putJson( repoEndpoint, url, toUpdateJsonObject.toString(), getUserAgent()); return (T) initializeFromJSONObject(updatedJsonObject, getAccessRequirementClassFromType(ar.getConcreteType())); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public ACTAccessRequirement createLockAccessRequirement(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); JSONObject jsonObj = getSharedClientConnection().postUri(repoEndpoint, ENTITY + "/" + entityId + LOCK_ACCESS_REQUIREMENT, getUserAgent()); return initializeFromJSONObject(jsonObj, ACTAccessRequirement.class); } @Override public void deleteAccessRequirement(Long arId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ACCESS_REQUIREMENT + "/" + arId, getUserAgent()); } @Override public PaginatedResults<AccessRequirement> getUnmetAccessRequirements( RestrictableObjectDescriptor subjectId, ACCESS_TYPE accessType) throws SynapseException { String uri = null; if (RestrictableObjectType.ENTITY == subjectId.getType()) { uri = ENTITY + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else if (RestrictableObjectType.EVALUATION == subjectId.getType()) { uri = EVALUATION_URI_PATH + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else if (RestrictableObjectType.TEAM == subjectId.getType()) { uri = TEAM + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else { throw new SynapseClientException("Unsupported type " + subjectId.getType()); } if (accessType != null) { uri += "?" + ACCESS_TYPE_PARAMETER + "=" + accessType; } JSONObject jsonAccessRequirements = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl( jsonAccessRequirements); PaginatedResults<AccessRequirement> results = new PaginatedResults<AccessRequirement>(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessRequirement getAccessRequirement(Long requirementId) throws SynapseException { String uri = ACCESS_REQUIREMENT + "/" + requirementId; JSONObject jsonObj = getEntity(uri); try { return EntityFactory.createEntityFromJSONObject(jsonObj, AccessRequirement.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<AccessRequirement> getAccessRequirements( RestrictableObjectDescriptor subjectId) throws SynapseException { String uri = null; if (RestrictableObjectType.ENTITY == subjectId.getType()) { uri = ENTITY + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else if (RestrictableObjectType.EVALUATION == subjectId.getType()) { uri = EVALUATION_URI_PATH + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else if (RestrictableObjectType.TEAM == subjectId.getType()) { uri = TEAM + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else { throw new SynapseClientException("Unsupported type " + subjectId.getType()); } JSONObject jsonAccessRequirements = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl( jsonAccessRequirements); PaginatedResults<AccessRequirement> results = new PaginatedResults<AccessRequirement>(AccessRequirement.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") private static Class<AccessApproval> getAccessApprovalClassFromType(String s) { try { return (Class<AccessApproval>) Class.forName(s); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessApproval> T createAccessApproval(T aa) throws SynapseException { if (aa == null) throw new IllegalArgumentException("AccessApproval cannot be null"); aa.setConcreteType(aa.getClass().getName()); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(aa); // Create the entity jsonObject = createJSONObject(ACCESS_APPROVAL, jsonObject); // Now convert to Object to an entity return (T) initializeFromJSONObject(jsonObject, getAccessApprovalClassFromType(aa.getConcreteType())); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessApproval getAccessApproval(Long approvalId) throws SynapseException { String uri = ACCESS_APPROVAL + "/" + approvalId; JSONObject jsonObj = getEntity(uri); try { return EntityFactory.createEntityFromJSONObject(jsonObj, AccessApproval.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public PaginatedResults<AccessApproval> getEntityAccessApproval(String entityId) throws SynapseException { String uri = ENTITY + "/" + entityId + "/" + ACCESS_APPROVAL; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<AccessApproval> results = new PaginatedResults<AccessApproval>(AccessApproval.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteAccessApproval(Long approvalId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ACCESS_APPROVAL + "/" + approvalId, getUserAgent()); } @Override public void deleteAccessApprovals(String requirementId, String accessorId) throws SynapseException { String url = ACCESS_APPROVAL + "?requirementId=" + requirementId + "&accessorId=" + accessorId; getSharedClientConnection().deleteUri(repoEndpoint, url, getUserAgent()); } /** * Get a dataset, layer, preview, annotations, etc... * * @return the retrieved entity */ @Override public JSONObject getEntity(String uri) throws SynapseException { return getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); } /** * Get an entity given an Entity ID and the class of the Entity. * * @param <T> * @param entityId * @param clazz * @return the entity * @throws SynapseException */ @Override @SuppressWarnings("cast") public <T extends JSONEntity> T getEntity(String entityId, Class<? extends T> clazz) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (clazz == null) throw new IllegalArgumentException("Entity class cannot be null"); // Build the URI String uri = createEntityUri(ENTITY_URI_PATH, entityId); JSONObject jsonObj = getEntity(uri); // Now convert to Object to an entity try { return (T) EntityFactory.createEntityFromJSONObject(jsonObj, clazz); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Helper to create an Entity URI. * * @param prefix * @param id * @return */ private static String createEntityUri(String prefix, String id) { StringBuilder uri = new StringBuilder(); uri.append(prefix); uri.append("/"); uri.append(id); return uri.toString(); } /** * Update a dataset, layer, preview, annotations, etc... * * @param <T> * @param entity * @return the updated entity * @throws SynapseException */ @Override public <T extends Entity> T putEntity(T entity) throws SynapseException { return putEntity(entity, null); } /** * Update a dataset, layer, preview, annotations, etc... * * @param <T> * @param entity * @param activityId * activity to create generatedBy conenction to * @return the updated entity * @throws SynapseException */ @Override @SuppressWarnings("unchecked") public <T extends Entity> T putEntity(T entity, String activityId) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); try { String uri = createEntityUri(ENTITY_URI_PATH, entity.getId()); if (activityId != null) uri += "?" + PARAM_GENERATED_BY + "=" + activityId; JSONObject jsonObject; jsonObject = EntityFactory.createJSONObjectForEntity(entity); jsonObject = getSharedClientConnection().putJson(repoEndpoint, uri, jsonObject.toString(), getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Deletes a dataset, layer, etc.. This only moves the entity to the trash * can. To permanently delete the entity, use deleteAndPurgeEntity(). */ @Override public <T extends Entity> void deleteEntity(T entity) throws SynapseException { deleteEntity(entity, null); } /** * Deletes a dataset, layer, etc.. By default, it moves the entity to the * trash can. There is the option to skip the trash and delete the entity * permanently. */ @Override public <T extends Entity> void deleteEntity(T entity, Boolean skipTrashCan) throws SynapseException { if (entity == null) { throw new IllegalArgumentException("Entity cannot be null"); } deleteEntityById(entity.getId(), skipTrashCan); } /** * Deletes a dataset, layer, etc.. */ @Override public <T extends Entity> void deleteAndPurgeEntity(T entity) throws SynapseException { deleteEntity(entity); purgeTrashForUser(entity.getId()); } /** * Deletes a dataset, layer, etc.. This only moves the entity to the trash * can. To permanently delete the entity, use deleteAndPurgeEntity(). */ @Override public void deleteEntityById(String entityId) throws SynapseException { deleteEntityById(entityId, null); } /** * Deletes a dataset, layer, etc.. By default, it moves the entity to the * trash can. There is the option to skip the trash and delete the entity * permanently. */ @Override public void deleteEntityById(String entityId, Boolean skipTrashCan) throws SynapseException { if (entityId == null) { throw new IllegalArgumentException("entityId cannot be null"); } String uri = createEntityUri(ENTITY_URI_PATH, entityId); if (skipTrashCan != null && skipTrashCan) { uri = uri + "?" + ServiceConstants.SKIP_TRASH_CAN_PARAM + "=true"; } getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Deletes a dataset, layer, etc.. */ @Override public void deleteAndPurgeEntityById(String entityId) throws SynapseException { deleteEntityById(entityId); purgeTrashForUser(entityId); } @Override public <T extends Entity> void deleteEntityVersion(T entity, Long versionNumber) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); deleteEntityVersionById(entity.getId(), versionNumber); } @Override public void deleteEntityVersionById(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (versionNumber == null) throw new IllegalArgumentException("VersionNumber cannot be null"); String uri = createEntityUri(ENTITY_URI_PATH, entityId); uri += REPO_SUFFIX_VERSION + "/" + versionNumber; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Get the hierarchical path to this entity * * @param entity * @return * @throws SynapseException */ @Override public EntityPath getEntityPath(Entity entity) throws SynapseException { return getEntityPath(entity.getId()); } /** * Get the hierarchical path to this entity via its id and urlPrefix * * @param entityId * @param urlPrefix * @return * @throws SynapseException */ @Override public EntityPath getEntityPath(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/path"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); EntityPath path = new EntityPath(); try { path.initializeFromJSONObject(adapter); return path; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<EntityHeader> getEntityTypeBatch(List<String> entityIds) throws SynapseException { String url = ENTITY_URI_PATH + "/type"; // TODO move UrlHelpers // someplace shared so that we // can UrlHelpers.ENTITY_TYPE url += "?" + ServiceConstants.BATCH_PARAM + "=" + StringUtils.join(entityIds, ServiceConstants.BATCH_PARAM_VALUE_SEPARATOR); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<EntityHeader> getEntityHeaderBatch( List<Reference> references) throws SynapseException { ReferenceList list = new ReferenceList(); list.setReferences(references); String url = ENTITY_URI_PATH + "/header"; JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(list); // POST jsonObject = createJSONObject(url, jsonObject); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Perform a query * * @param query * the query to perform * @return the query result * @throws SynapseException */ @Override public JSONObject query(String query) throws SynapseException { return querySynapse(query); } @Override @Deprecated public FileHandleResults createFileHandles(List<File> files) throws SynapseException { if (files == null) throw new IllegalArgumentException("File list cannot be null"); try { List<FileHandle> list = new LinkedList<FileHandle>(); for (File file : files) { // We need to determine the content type of the file String contentType = guessContentTypeFromStream(file); S3FileHandle handle = createFileHandle(file, contentType); list.add(handle); } FileHandleResults results = new FileHandleResults(); results.setList(list); return results; } catch (IOException e) { throw new SynapseClientException(e); } } @Override public FileHandleResults createFileHandles(List<File> files, String parentEntityId) throws SynapseException { if (files == null) throw new IllegalArgumentException("File list cannot be null"); try { List<FileHandle> list = new LinkedList<FileHandle>(); for (File file : files) { // We need to determine the content type of the file String contentType = guessContentTypeFromStream(file); FileHandle handle = createFileHandle(file, contentType, parentEntityId); list.add(handle); } FileHandleResults results = new FileHandleResults(); results.setList(list); return results; } catch (IOException e) { throw new SynapseClientException(e); } } @Override public URL getFileHandleTemporaryUrl(String fileHandleId) throws IOException, SynapseException { String uri = getFileHandleTemporaryURI(fileHandleId, false); return getUrl(getFileEndpoint(), uri); } private String getFileHandleTemporaryURI(String fileHandleId, boolean redirect) { return FILE_HANDLE + "/" + fileHandleId + "/url" + QUERY_REDIRECT_PARAMETER + redirect; } @Override public void downloadFromFileHandleTemporaryUrl(String fileHandleId, File destinationFile) throws SynapseException { String uri = getFileEndpoint() + getFileHandleTemporaryURI(fileHandleId, true); getSharedClientConnection().downloadFromSynapse(uri, null, destinationFile, getUserAgent()); } @Override @Deprecated public S3FileHandle createFileHandle(File temp, String contentType) throws SynapseException, IOException { return createFileHandleUsingChunkedUpload(temp, contentType, null, null); } @Override @Deprecated public S3FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated) throws SynapseException, IOException { return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, null); } @Override public FileHandle createFileHandle(File temp, String contentType, String parentEntityId) throws SynapseException, IOException { return createFileHandle(temp, contentType, null, parentEntityId); } @Override public FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, String parentEntityId) throws SynapseException, IOException { UploadDestination uploadDestination = getDefaultUploadDestination(parentEntityId); return createFileHandle(temp, contentType, shouldPreviewBeCreated, uploadDestination.getStorageLocationId(), uploadDestination.getUploadType()); } @Override public FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, String parentEntityId, Long storageLocationId) throws SynapseException, IOException { UploadDestination uploadDestination = getUploadDestination(parentEntityId, storageLocationId); return createFileHandle(temp, contentType, shouldPreviewBeCreated, storageLocationId, uploadDestination.getUploadType()); } private FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, Long storageLocationId, UploadType uploadType) throws SynapseException, IOException { if (storageLocationId == null) { // default to S3 return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, null); } switch (uploadType) { case HTTPS: case SFTP: throw new NotImplementedException("SFTP and HTTPS uploads not implemented yet"); case S3: return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, storageLocationId); default: throw new NotImplementedException(uploadType.name() + " uploads not implemented yet"); } } private S3FileHandle createFileHandleUsingChunkedUpload(File temp, String contentType, Boolean shouldPreviewBeCreated, Long storageLocationId) throws SynapseException, IOException { if (temp == null) { throw new IllegalArgumentException("File cannot be null"); } if (contentType == null) { throw new IllegalArgumentException("Content type cannot be null"); } CreateChunkedFileTokenRequest ccftr = new CreateChunkedFileTokenRequest(); ccftr.setStorageLocationId(storageLocationId); ccftr.setContentType(contentType); ccftr.setFileName(temp.getName()); // Calculate the MD5 String md5 = MD5ChecksumHelper.getMD5Checksum(temp); ccftr.setContentMD5(md5); // Start the upload ChunkedFileToken token = createChunkedFileUploadToken(ccftr); // Now break the file into part as needed List<File> fileChunks = FileUtils.chunkFile(temp, MINIMUM_CHUNK_SIZE_BYTES); try { // Upload all of the parts. List<Long> partNumbers = uploadChunks(fileChunks, token); // We can now complete the upload CompleteAllChunksRequest cacr = new CompleteAllChunksRequest(); cacr.setChunkedFileToken(token); cacr.setChunkNumbers(partNumbers); cacr.setShouldPreviewBeGenerated(shouldPreviewBeCreated); // Start the daemon UploadDaemonStatus status = startUploadDeamon(cacr); // Wait for it to complete long start = System.currentTimeMillis(); while (State.COMPLETED != status.getState()) { // Check for failure if (State.FAILED == status.getState()) { throw new SynapseClientException("Upload failed: " + status.getErrorMessage()); } log.debug("Waiting for upload daemon: " + status.toString()); Thread.sleep(1000); status = getCompleteUploadDaemonStatus(status.getDaemonId()); if (System.currentTimeMillis() - start > MAX_UPLOAD_DAEMON_MS) { throw new SynapseClientException( "Timed out waiting for upload daemon: " + status.toString()); } } // Complete the upload return (S3FileHandle) getRawFileHandle(status.getFileHandleId()); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { // Delete any tmep files created by this method. The original file // will not be deleted. FileUtils.deleteAllFilesExcludingException(temp, fileChunks); } } /** * Upload all of the passed file chunks. * * @param fileChunks * @param token * @return * @throws ExecutionException * @throws InterruptedException */ private List<Long> uploadChunks(List<File> fileChunks, ChunkedFileToken token) throws SynapseException { try { List<Long> results = new LinkedList<Long>(); // The future list List<Future<Long>> futureList = new ArrayList<Future<Long>>(); // For each chunk create a worker and add it to the thread pool long chunkNumber = 1; for (File file : fileChunks) { // create a worker for each chunk ChunkRequest request = new ChunkRequest(); request.setChunkedFileToken(token); request.setChunkNumber(chunkNumber); FileChunkUploadWorker worker = new FileChunkUploadWorker(this, request, file); // Add this the the thread pool Future<Long> future = fileUplaodthreadPool.submit(worker); futureList.add(future); chunkNumber++; } // Get all of the results for (Future<Long> future : futureList) { Long partNumber = future.get(); results.add(partNumber); } return results; } catch (Exception e) { throw new SynapseClientException(e); } } /** * <P> * This is a low-level API call for uploading large files. We recomend using * the high-level API call for uploading files * {@link #createFileHandle(File, String)}. * </P> * This is the first step in the low-level API used to upload large files to * Synapse. The resulting {@link ChunkedFileToken} is required for all * subsequent steps. Large file upload is exectued as follows: * <ol> * <li>{@link #createChunkedFileUploadToken(CreateChunkedFileTokenRequest)}</li> * <li>{@link #createChunkedPresignedUrl(ChunkRequest)}</li> * <li>{@link #addChunkToFile(ChunkRequest)}</li> * <li>{@link #completeChunkFileUpload(CompleteChunkedFileRequest)}</li> * </ol> * Steps 2 & 3 are repated in for each file chunk. Note: All chunks can be * sent asynchronously. * * @param ccftr * @return The @link {@link ChunkedFileToken} is required for all subsequent * steps. * @throws JSONObjectAdapterException * @throws SynapseException * @throws IOException * @throws ClientProtocolException */ @Override public ChunkedFileToken createChunkedFileUploadToken( CreateChunkedFileTokenRequest ccftr) throws SynapseException { if (ccftr == null) throw new IllegalArgumentException( "CreateChunkedFileTokenRequest cannot be null"); if (ccftr.getFileName() == null) throw new IllegalArgumentException("FileName cannot be null"); if (ccftr.getContentType() == null) throw new IllegalArgumentException("ContentType cannot be null"); String url = CREATE_CHUNKED_FILE_UPLOAD_TOKEN; return asymmetricalPost(getFileEndpoint(), url, ccftr, ChunkedFileToken.class, null); } /** * <P> * This is a low-level API call for uploading large files. We recomend using * the high-level API call for uploading files * {@link #createFileHandle(File, String)}. * </P> * The second step in the low-level API used to upload large files to * Synapse. This method is used to get a pre-signed URL that can be used to * PUT the data of a single chunk to S3. * * @param chunkRequest * @return * @throws JSONObjectAdapterException * @throws IOException * @throws ClientProtocolException */ @Override public URL createChunkedPresignedUrl(ChunkRequest chunkRequest) throws SynapseException { try { if (chunkRequest == null) { throw new IllegalArgumentException( "ChunkRequest cannot be null"); } String uri = CREATE_CHUNKED_FILE_UPLOAD_CHUNK_URL; String data = EntityFactory.createJSONStringForEntity(chunkRequest); String responseBody = getSharedClientConnection().postStringDirect( getFileEndpoint(), uri, data, getUserAgent()); return new URL(responseBody); } catch (IOException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Put the contents of the passed file to the passed URL. * * @param url * @param file * @throws IOException * @throws ClientProtocolException */ @Override public String putFileToURL(URL url, File file, String contentType) throws SynapseException { return getHttpClientHelper().putFileToURL(url, file, contentType); } /** * Start a daemon that will asycnrhounsously complete the multi-part upload. * * @param cacr * @return * @throws SynapseException */ @Override public UploadDaemonStatus startUploadDeamon(CompleteAllChunksRequest cacr) throws SynapseException { String url = START_COMPLETE_UPLOAD_DAEMON; return asymmetricalPost(getFileEndpoint(), url, cacr, UploadDaemonStatus.class, null); } /** * Get the status of daemon used to complete the multi-part upload. * * @param daemonId * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public UploadDaemonStatus getCompleteUploadDaemonStatus(String daemonId) throws SynapseException { String url = COMPLETE_UPLOAD_DAEMON_STATUS + "/" + daemonId; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { return EntityFactory.createEntityFromJSONObject(json, UploadDaemonStatus.class); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } /** * Create an External File Handle. This is used to references a file that is * not stored in Synpase. * * @param efh * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public ExternalFileHandle createExternalFileHandle(ExternalFileHandle efh) throws JSONObjectAdapterException, SynapseException { String uri = EXTERNAL_FILE_HANDLE; return doCreateJSONEntity(getFileEndpoint(), uri, efh); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#createExternalS3FileHandle(org.sagebionetworks.repo.model.file.S3FileHandle) */ @Override public S3FileHandle createExternalS3FileHandle(S3FileHandle handle) throws JSONObjectAdapterException, SynapseException{ String uri = EXTERNAL_FILE_HANDLE_S3; return doCreateJSONEntity(getFileEndpoint(), uri, handle); } @Override public ProxyFileHandle createExternalProxyFileHandle(ProxyFileHandle handle) throws JSONObjectAdapterException, SynapseException{ return doCreateJSONEntity(getFileEndpoint(), EXTERNAL_FILE_HANDLE_PROXY, handle); } @Override public S3FileHandle createS3FileHandleCopy(String originalFileHandleId, String name, String contentType) throws JSONObjectAdapterException, SynapseException { String uri = FILE_HANDLE + "/" + originalFileHandleId + "/copy"; S3FileHandle changes = new S3FileHandle(); changes.setFileName(name); changes.setContentType(contentType); return doCreateJSONEntity(getFileEndpoint(), uri, changes); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#startBulkFileDownload(org.sagebionetworks.repo.model.file.BulkFileDownloadRequest) */ @Override public String startBulkFileDownload(BulkFileDownloadRequest request) throws SynapseException{ return startAsynchJob(AsynchJobType.BulkFileDownload, request); } @Override public BulkFileDownloadResponse getBulkFileDownloadResults(String asyncJobToken) throws SynapseException, SynapseResultNotReadyException { return (BulkFileDownloadResponse) getAsyncResult(AsynchJobType.BulkFileDownload, asyncJobToken, (String) null); } /** * Asymmetrical post where the request and response are not of the same * type. * * @param url * @param reqeust * @param calls * @throws SynapseException */ private <T extends JSONEntity> T asymmetricalPost(String endpoint, String url, JSONEntity requestBody, Class<? extends T> returnClass, SharedClientConnection.ErrorHandler errorHandler) throws SynapseException { try { String jsonString = EntityFactory .createJSONStringForEntity(requestBody); JSONObject responseBody = getSharedClientConnection().postJson( endpoint, url, jsonString, getUserAgent(), null, errorHandler); return EntityFactory.createEntityFromJSONObject(responseBody, returnClass); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Asymmetrical put where the request and response are not of the same * type. * * @param url * @param reqeust * @param calls * @throws SynapseException */ private <T extends JSONEntity> T asymmetricalPut(String endpoint, String url, JSONEntity requestBody, Class<? extends T> returnClass) throws SynapseException { try { String jsonString = null; if(requestBody != null){ jsonString = EntityFactory .createJSONStringForEntity(requestBody); } JSONObject responseBody = getSharedClientConnection().putJson( endpoint, url, jsonString, getUserAgent()); return EntityFactory.createEntityFromJSONObject(responseBody, returnClass); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the raw file handle. Note: Only the creator of a the file handle can * get the raw file handle. * * @param fileHandleId * @return * @throws SynapseException */ @Override public FileHandle getRawFileHandle(String fileHandleId) throws SynapseException { JSONObject object = getSharedClientConnection().getJson( getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId, getUserAgent()); try { return EntityFactory.createEntityFromJSONObject(object, FileHandle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Delete a raw file handle. Note: Only the creator of a the file handle can * delete the file handle. * * @param fileHandleId * @throws SynapseException */ @Override public void deleteFileHandle(String fileHandleId) throws SynapseException { getSharedClientConnection().deleteUri(getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId, getUserAgent()); } /** * Delete the preview associated with the given file handle. Note: Only the * creator of a the file handle can delete the preview. * * @param fileHandleId * @throws SynapseException */ @Override public void clearPreview(String fileHandleId) throws SynapseException { getSharedClientConnection() .deleteUri(getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId + FILE_PREVIEW, getUserAgent()); } /** * Guess the content type of a file by reading the start of the file stream * using URLConnection.guessContentTypeFromStream(is); If URLConnection * fails to return a content type then "application/octet-stream" will be * returned. * * @param file * @return * @throws FileNotFoundException * @throws IOException */ public static String guessContentTypeFromStream(File file) throws FileNotFoundException, IOException { InputStream is = new BufferedInputStream(new FileInputStream(file)); try { // Let java guess from the stream. String contentType = URLConnection.guessContentTypeFromStream(is); // If Java fails then set the content type to be octet-stream if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } return contentType; } finally { is.close(); } } /** * * Create a wiki page for a given owner object. * * @param ownerId * @param ownerType * @param toCreate * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public WikiPage createWikiPage(String ownerId, ObjectType ownerType, WikiPage toCreate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toCreate == null) throw new IllegalArgumentException("WikiPage cannot be null"); String uri = createWikiURL(ownerId, ownerType); return doCreateJSONEntity(uri, toCreate); } /** * Helper to create a wiki URL that does not include the wiki id. * * @param ownerId * @param ownerType * @return */ private String createWikiURL(String ownerId, ObjectType ownerType) { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); return String.format(WIKI_URI_TEMPLATE, ownerType.name().toLowerCase(), ownerId); } /** * Get a WikiPage using its key * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public WikiPage getWikiPage(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key); return getJSONEntity(uri, WikiPage.class); } @Override public WikiPage getWikiPageForVersion(WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { String uri = createWikiURL(key) + VERSION_PARAMETER + version; return getJSONEntity(uri, WikiPage.class); } @Override public WikiPageKey getRootWikiPageKey(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createWikiURL(ownerId, ownerType)+"key"; return getJSONEntity(uri, WikiPageKey.class); } /** * Get a the root WikiPage for a given owner. * * @param ownerId * @param ownerType * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public WikiPage getRootWikiPage(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createWikiURL(ownerId, ownerType); return getJSONEntity(uri, WikiPage.class); } /** * Get all of the FileHandles associated with a WikiPage, including any * PreviewHandles. * * @param key * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getWikiAttachmenthHandles(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key) + ATTACHMENT_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } private static String createWikiAttachmentURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createWikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a WikiPage attachment. This is an alternative * to downloading the attachment to a file. * * @param key * - Identifies a wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getWikiAttachmentTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createWikiAttachmentURI(key, fileName, false)); } @Override public void downloadWikiAttachment(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createWikiAttachmentURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createWikiAttachmentPreviewURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createWikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a WikiPage attachment preview. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getWikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createWikiAttachmentPreviewURI(key, fileName, false)); } @Override public void downloadWikiAttachmentPreview(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createWikiAttachmentPreviewURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for the current * version of the entity.. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityTemporaryUrlForCurrentVersion(String entityId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityCurrentVersion(String fileEntityId, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + fileEntityId + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file preview of a FileEntity for the * current version of the entity.. This is an alternative to downloading the * file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityPreviewTemporaryUrlForCurrentVersion(String entityId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityPreviewCurrentVersion( String fileEntityId, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + fileEntityId + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for a given * version number. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityTemporaryUrlForVersion(String entityId, Long versionNumber) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityForVersion(String entityId, Long versionNumber, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for a given * version number. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityPreviewTemporaryUrlForVersion(String entityId, Long versionNumber) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityPreviewForVersion(String entityId, Long versionNumber, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Fetch a temporary url. * * @param uri * @return * @throws ClientProtocolException * @throws IOException * @throws MalformedURLException * @throws SynapseException */ private URL getUrl(String uri) throws ClientProtocolException, IOException, MalformedURLException, SynapseException { return new URL(getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent())); } private URL getUrl(String endpoint, String uri) throws ClientProtocolException, IOException, MalformedURLException, SynapseException { return new URL(getSharedClientConnection().getDirect(endpoint, uri, getUserAgent())); } /** * Update a WikiPage * * @param ownerId * @param ownerType * @param toUpdate * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public WikiPage updateWikiPage(String ownerId, ObjectType ownerType, WikiPage toUpdate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toUpdate == null) throw new IllegalArgumentException("WikiPage cannot be null"); if (toUpdate.getId() == null) throw new IllegalArgumentException( "WikiPage.getId() cannot be null"); String uri = String.format(WIKI_ID_URI_TEMPLATE, ownerType.name() .toLowerCase(), ownerId, toUpdate.getId()); return updateJSONEntity(uri, toUpdate); } /** * Delete a WikiPage * * @param key * @throws SynapseException */ @Override public void deleteWikiPage(WikiPageKey key) throws SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Helper to build a URL for a wiki page. * * @param key * @return */ private static String createWikiURL(WikiPageKey key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); return String.format(WIKI_ID_URI_TEMPLATE, key.getOwnerObjectType() .name().toLowerCase(), key.getOwnerObjectId(), key.getWikiPageId()); } /** * Get the WikiHeader tree for a given owner object. * * @param ownerId * @param ownerType * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<WikiHeader> getWikiHeaderTree(String ownerId, ObjectType ownerType) throws SynapseException, JSONObjectAdapterException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = String.format(WIKI_TREE_URI_TEMPLATE, ownerType.name() .toLowerCase(), ownerId); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<WikiHeader> paginated = new PaginatedResults<WikiHeader>( WikiHeader.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } /** * Get the file handles for the current version of an entity. * * @param entityId * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getEntityFileHandlesForCurrentVersion( String entityId) throws JSONObjectAdapterException, SynapseException { if (entityId == null) throw new IllegalArgumentException("Key cannot be null"); String uri = ENTITY_URI_PATH + "/" + entityId + FILE_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } /** * Get the file hanldes for a given version of an entity. * * @param entityId * @param versionNumber * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getEntityFileHandlesForVersion(String entityId, Long versionNumber) throws JSONObjectAdapterException, SynapseException { if (entityId == null) throw new IllegalArgumentException("Key cannot be null"); String uri = ENTITY_URI_PATH + "/" + entityId + "/version/" + versionNumber + FILE_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } // V2 WIKIPAGE METHODS /** * Helper to create a V2 Wiki URL (No ID) */ private String createV2WikiURL(String ownerId, ObjectType ownerType) { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); return String.format(WIKI_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId); } /** * Helper to build a URL for a V2 Wiki page, with ID * * @param key * @return */ private static String createV2WikiURL(WikiPageKey key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); return String.format(WIKI_ID_URI_TEMPLATE_V2, key.getOwnerObjectType() .name().toLowerCase(), key.getOwnerObjectId(), key.getWikiPageId()); } /** * * Create a V2 WikiPage for a given owner object. * * @param ownerId * @param ownerType * @param toCreate * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public V2WikiPage createV2WikiPage(String ownerId, ObjectType ownerType, V2WikiPage toCreate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toCreate == null) throw new IllegalArgumentException("WikiPage cannot be null"); String uri = createV2WikiURL(ownerId, ownerType); return doCreateJSONEntity(uri, toCreate); } /** * Get a V2 WikiPage using its key * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public V2WikiPage getV2WikiPage(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key); return getJSONEntity(uri, V2WikiPage.class); } /** * Get a version of a V2 WikiPage using its key and version number */ @Override public V2WikiPage getVersionOfV2WikiPage(WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + VERSION_PARAMETER + version; return getJSONEntity(uri, V2WikiPage.class); } /** * Get a the root V2 WikiPage for a given owner. * * @param ownerId * @param ownerType * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage getV2RootWikiPage(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createV2WikiURL(ownerId, ownerType); return getJSONEntity(uri, V2WikiPage.class); } /** * Update a V2 WikiPage * * @param ownerId * @param ownerType * @param toUpdate * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage updateV2WikiPage(String ownerId, ObjectType ownerType, V2WikiPage toUpdate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toUpdate == null) throw new IllegalArgumentException("WikiPage cannot be null"); if (toUpdate.getId() == null) throw new IllegalArgumentException( "WikiPage.getId() cannot be null"); String uri = String.format(WIKI_ID_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId, toUpdate.getId()); return updateJSONEntity(uri, toUpdate); } @Override public V2WikiOrderHint updateV2WikiOrderHint(V2WikiOrderHint toUpdate) throws JSONObjectAdapterException, SynapseException { if (toUpdate == null) throw new IllegalArgumentException("toUpdate cannot be null"); if (toUpdate.getOwnerId() == null) throw new IllegalArgumentException( "V2WikiOrderHint.getOwnerId() cannot be null"); if (toUpdate.getOwnerObjectType() == null) throw new IllegalArgumentException( "V2WikiOrderHint.getOwnerObjectType() cannot be null"); String uri = String.format(WIKI_ORDER_HINT_URI_TEMPLATE_V2, toUpdate .getOwnerObjectType().name().toLowerCase(), toUpdate.getOwnerId()); return updateJSONEntity(uri, toUpdate); } /** * Restore contents of a V2 WikiPage to the contents of a particular * version. * * @param ownerId * @param ownerType * @param wikiId * @param versionToRestore * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage restoreV2WikiPage(String ownerId, ObjectType ownerType, String wikiId, Long versionToRestore) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (wikiId == null) throw new IllegalArgumentException("Wiki id cannot be null"); if (versionToRestore == null) throw new IllegalArgumentException("Version cannot be null"); String uri = String.format(WIKI_ID_VERSION_URI_TEMPLATE_V2, ownerType .name().toLowerCase(), ownerId, wikiId, String .valueOf(versionToRestore)); V2WikiPage mockWikiToUpdate = new V2WikiPage(); return updateJSONEntity(uri, mockWikiToUpdate); } /** * Get all of the FileHandles associated with a V2 WikiPage, including any * PreviewHandles. * * @param key * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getV2WikiAttachmentHandles(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + ATTACHMENT_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } @Override public FileHandleResults getVersionOfV2WikiAttachmentHandles( WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + ATTACHMENT_HANDLES + VERSION_PARAMETER + version; return getJSONEntity(uri, FileHandleResults.class); } @Override public String downloadV2WikiMarkdown(WikiPageKey key) throws ClientProtocolException, FileNotFoundException, IOException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + MARKDOWN_FILE; return getSharedClientConnection().downloadZippedFileString( repoEndpoint, uri, getUserAgent()); } @Override public String downloadVersionOfV2WikiMarkdown(WikiPageKey key, Long version) throws ClientProtocolException, FileNotFoundException, IOException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + MARKDOWN_FILE + VERSION_PARAMETER + version; return getSharedClientConnection().downloadZippedFileString( repoEndpoint, uri, getUserAgent()); } private static String createV2WikiAttachmentURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a V2 WikiPage attachment. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a V2 wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getV2WikiAttachmentTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createV2WikiAttachmentURI(key, fileName, false)); } @Override public void downloadV2WikiAttachment(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createV2WikiAttachmentURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createV2WikiAttachmentPreviewURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a V2 WikiPage attachment preview. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a V2 wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getV2WikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createV2WikiAttachmentPreviewURI(key, fileName, false)); } @Override public void downloadV2WikiAttachmentPreview(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createV2WikiAttachmentPreviewURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createVersionOfV2WikiAttachmentPreviewURI( WikiPageKey key, String fileName, Long version, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect + AND_VERSION_PARAMETER + version; } @Override public URL getVersionOfV2WikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName, Long version) throws ClientProtocolException, IOException, SynapseException { return getUrl(createVersionOfV2WikiAttachmentPreviewURI(key, fileName, version, false)); } @Override public void downloadVersionOfV2WikiAttachmentPreview(WikiPageKey key, String fileName, Long version, File target) throws SynapseException { String uri = createVersionOfV2WikiAttachmentPreviewURI(key, fileName, version, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createVersionOfV2WikiAttachmentURI(WikiPageKey key, String fileName, Long version, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect + AND_VERSION_PARAMETER + version; } @Override public URL getVersionOfV2WikiAttachmentTemporaryUrl(WikiPageKey key, String fileName, Long version) throws ClientProtocolException, IOException, SynapseException { return getUrl(createVersionOfV2WikiAttachmentURI(key, fileName, version, false)); } // alternative to getVersionOfV2WikiAttachmentTemporaryUrl @Override public void downloadVersionOfV2WikiAttachment(WikiPageKey key, String fileName, Long version, File target) throws SynapseException { String uri = createVersionOfV2WikiAttachmentURI(key, fileName, version, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Delete a V2 WikiPage * * @param key * @throws SynapseException */ @Override public void deleteV2WikiPage(WikiPageKey key) throws SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public V2WikiPage deleteV2WikiVersions(WikiPageKey key, WikiVersionsList versionsToDelete) throws SynapseException, JSONObjectAdapterException { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } if (versionsToDelete == null) { throw new IllegalArgumentException("VersionsToDelete cannot be null"); } String uri = createV2WikiURL(key) + "/markdown/deleteversion"; String postJSON = EntityFactory.createJSONStringForEntity(versionsToDelete); JSONObject jsonObject = getSharedClientConnection().putJson(repoEndpoint, uri, postJSON, getUserAgent()); return EntityFactory.createEntityFromJSONObject(jsonObject, V2WikiPage.class); } /** * Get the WikiHeader tree for a given owner object. * * @param ownerId * @param ownerType * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<V2WikiHeader> getV2WikiHeaderTree(String ownerId, ObjectType ownerType) throws SynapseException, JSONObjectAdapterException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = String.format(WIKI_TREE_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<V2WikiHeader> paginated = new PaginatedResults<V2WikiHeader>( V2WikiHeader.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } @Override public V2WikiOrderHint getV2OrderHint(WikiPageKey key) throws SynapseException, JSONObjectAdapterException { if (key == null) throw new IllegalArgumentException("key cannot be null"); String uri = String.format(WIKI_ORDER_HINT_URI_TEMPLATE_V2, key .getOwnerObjectType().name().toLowerCase(), key.getOwnerObjectId()); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); V2WikiOrderHint orderHint = new V2WikiOrderHint(); orderHint.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return orderHint; } /** * Get the tree of snapshots (outlining each modification) for a particular * V2 WikiPage * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<V2WikiHistorySnapshot> getV2WikiHistory( WikiPageKey key, Long limit, Long offset) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + WIKI_HISTORY_V2 + "?" + OFFSET_PARAMETER + offset + AND_LIMIT_PARAMETER + limit; JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<V2WikiHistorySnapshot> paginated = new PaginatedResults<V2WikiHistorySnapshot>( V2WikiHistorySnapshot.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } public File downloadFromSynapse(String path, String md5, File destinationFile) throws SynapseException { return getSharedClientConnection().downloadFromSynapse(path, md5, destinationFile, null); } /******************** Low Level APIs ********************/ /** * Create any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") <T extends JSONEntity> T doCreateJSONEntity(String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String postJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().postJson( repoEndpoint, uri, postJSON, getUserAgent(), null); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Create any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") private <T extends JSONEntity> T doCreateJSONEntity(String endpoint, String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String postJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().postJson(endpoint, uri, postJSON, getUserAgent(), null); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Update any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") private <T extends JSONEntity> T updateJSONEntity(String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String putJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().putJson( repoEndpoint, uri, putJSON, getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Get a JSONEntity */ protected <T extends JSONEntity> T getJSONEntity(String uri, Class<? extends T> clazz) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == clazz) { throw new IllegalArgumentException("must provide entity"); } JSONObject jsonObject = getSharedClientConnection().getJson( repoEndpoint, uri, getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, clazz); } /** * Get a dataset, layer, preview, annotations, etc... * * @return the retrieved entity */ private JSONObject getSynapseEntity(String endpoint, String uri) throws SynapseException { if (null == endpoint) { throw new IllegalArgumentException("must provide endpoint"); } if (null == uri) { throw new IllegalArgumentException("must provide uri"); } return getSharedClientConnection().getJson(endpoint, uri, getUserAgent()); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#startAsynchJob(org.sagebionetworks.client.AsynchJobType, org.sagebionetworks.repo.model.asynch.AsynchronousRequestBody) */ public String startAsynchJob(AsynchJobType type, AsynchronousRequestBody request) throws SynapseException { String url = type.getStartUrl(request); String endpoint = getEndpointForType(type.getRestEndpoint()); AsyncJobId jobId = asymmetricalPost(endpoint, url, request, AsyncJobId.class, null); return jobId.getToken(); } @Override public void cancelAsynchJob(String jobId) throws SynapseException { String url = ASYNCHRONOUS_JOB + "/" + jobId + "/cancel"; getSharedClientConnection().getJson(getRepoEndpoint(), url, getUserAgent()); } @Override public AsynchronousResponseBody getAsyncResult(AsynchJobType type, String jobId, AsynchronousRequestBody request) throws SynapseException, SynapseClientException, SynapseResultNotReadyException { String url = type.getResultUrl(jobId, request); String endpoint = getEndpointForType(type.getRestEndpoint()); return getAsynchJobResponse(url, type.getReponseClass(), endpoint); } @Override public AsynchronousResponseBody getAsyncResult(AsynchJobType type, String jobId, String entityId) throws SynapseException, SynapseClientException, SynapseResultNotReadyException { String url = type.getResultUrl(jobId, entityId); String endpoint = getEndpointForType(type.getRestEndpoint()); return getAsynchJobResponse(url, type.getReponseClass(), endpoint); } /** * Get a job response body for a url. * @param url * @param clazz * @return * @throws SynapseException */ private AsynchronousResponseBody getAsynchJobResponse(String url, Class<? extends AsynchronousResponseBody> clazz, String endpoint) throws SynapseException { JSONObject responseBody = getSharedClientConnection().getJson( endpoint, url, getUserAgent(), new SharedClientConnection.ErrorHandler() { @Override public void handleError(int code, String responseBody) throws SynapseException { if (code == HttpStatus.SC_ACCEPTED) { try { AsynchronousJobStatus status = EntityFactory .createEntityFromJSONString( responseBody, AsynchronousJobStatus.class); throw new SynapseResultNotReadyException( status); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e .getMessage(), e); } } } }); try { return EntityFactory.createEntityFromJSONObject(responseBody, clazz); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Update a dataset, layer, preview, annotations, etc... * * This convenience method first grabs a copy of the currently stored * entity, then overwrites fields from the entity passed in on top of the * stored entity we retrieved and then PUTs the entity. This essentially * does a partial update from the point of view of the user of this API. * * Note that users of this API may want to inspect what they are overwriting * before they do so. Another approach would be to do a GET, display the * field to the user, allow them to edit the fields, and then do a PUT. * * @param defaultEndpoint * @param uri * @param entity * @return the updated entity * @throws SynapseException */ @SuppressWarnings("unchecked") @Deprecated public JSONObject updateSynapseEntity(String uri, JSONObject entity) throws SynapseException { JSONObject storedEntity = getSharedClientConnection().getJson( repoEndpoint, uri, getUserAgent()); boolean isAnnotation = uri.endsWith(ANNOTATION_URI_SUFFIX); try { Iterator<String> keyIter = entity.keys(); while (keyIter.hasNext()) { String key = keyIter.next(); if (isAnnotation) { // Annotations need to go one level deeper JSONObject storedAnnotations = storedEntity .getJSONObject(key); JSONObject entityAnnotations = entity.getJSONObject(key); Iterator<String> annotationIter = entity.getJSONObject(key) .keys(); while (annotationIter.hasNext()) { String annotationKey = annotationIter.next(); storedAnnotations.put(annotationKey, entityAnnotations.get(annotationKey)); } } else { storedEntity.put(key, entity.get(key)); } } return getSharedClientConnection().putJson(repoEndpoint, uri, storedEntity.toString(), getUserAgent()); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Perform a query * * @param query * the query to perform * @return the query result */ private JSONObject querySynapse(String query) throws SynapseException { try { if (null == query) { throw new IllegalArgumentException("must provide a query"); } String queryUri; queryUri = QUERY_URI + URLEncoder.encode(query, "UTF-8"); return getSharedClientConnection().getJson(repoEndpoint, queryUri, getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } /** * @return status * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public StackStatus getCurrentStackStatus() throws SynapseException, JSONObjectAdapterException { JSONObject json = getEntity(STACK_STATUS); return EntityFactory .createEntityFromJSONObject(json, StackStatus.class); } @Override public SearchResults search(SearchQuery searchQuery) throws SynapseException, UnsupportedEncodingException, JSONObjectAdapterException { SearchResults searchResults = null; String uri = "/search"; String jsonBody = EntityFactory.createJSONStringForEntity(searchQuery); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); if (obj != null) { JSONObjectAdapter adapter = new JSONObjectAdapterImpl(obj); searchResults = new SearchResults(adapter); } return searchResults; } @Override public String getSynapseTermsOfUse() throws SynapseException { return getTermsOfUse(DomainType.SYNAPSE); } @Override public String getTermsOfUse(DomainType domain) throws SynapseException { if (domain == null) { throw new IllegalArgumentException("Domain must be specified"); } return getHttpClientHelper().getDataDirect(authEndpoint, "/" + domain.name().toLowerCase() + "TermsOfUse.html"); } /** * Helper for pagination of messages */ private String setMessageParameters(String path, List<MessageStatusType> inboxFilter, MessageSortBy orderBy, Boolean descending, Long limit, Long offset) { if (path == null) { throw new IllegalArgumentException("Path must be specified"); } URIBuilder builder = new URIBuilder(); builder.setPath(path); if (inboxFilter != null) { builder.setParameter(MESSAGE_INBOX_FILTER_PARAM, StringUtils.join(inboxFilter.toArray(), ',')); } if (orderBy != null) { builder.setParameter(MESSAGE_ORDER_BY_PARAM, orderBy.name()); } if (descending != null) { builder.setParameter(MESSAGE_DESCENDING_PARAM, "" + descending); } if (limit != null) { builder.setParameter(LIMIT, "" + limit); } if (offset != null) { builder.setParameter(OFFSET, "" + offset); } return builder.toString(); } @Override public MessageToUser sendMessage(MessageToUser message) throws SynapseException { String uri = MESSAGE; try { String jsonBody = EntityFactory.createJSONStringForEntity(message); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#uploadToFileHandle(byte[], org.apache.http.entity.ContentType, java.lang.String) */ @Override public String uploadToFileHandle(byte[] content, ContentType contentType, String parentEntityId) throws SynapseException { List<UploadDestination> uploadDestinations = getUploadDestinations(parentEntityId); if (uploadDestinations.isEmpty()) { // default to S3 return uploadToS3FileHandle(content, contentType, null); } UploadDestination uploadDestination = uploadDestinations.get(0); switch (uploadDestination.getUploadType()) { case HTTPS: case SFTP: throw new NotImplementedException( "SFTP and HTTPS uploads not implemented yet"); case S3: return uploadToS3FileHandle(content, contentType, (S3UploadDestination) uploadDestination); default: throw new NotImplementedException(uploadDestination.getUploadType() .name() + " uploads not implemented yet"); } } /** * uploads a String to S3 using the chunked file upload service * * @param content * the content to upload. Strings in memory should not be large, * so we limit to the size of one 'chunk' * @param contentType * should include the character encoding, e.g. * "text/plain; charset=utf-8" */ @Override public String uploadToFileHandle(byte[] content, ContentType contentType) throws SynapseException { return uploadToS3FileHandle(content, contentType, null); } /** * uploads a String to S3 using the chunked file upload service * * @param content * the content to upload. Strings in memory should not be large, * so we limit to the size of one 'chunk' * @param contentType * should include the character encoding, e.g. * "text/plain; charset=utf-8" */ private String uploadToS3FileHandle(byte[] content, ContentType contentType, UploadDestination uploadDestination) throws SynapseClientException, SynapseException { if (content == null || content.length == 0) throw new IllegalArgumentException("Missing content."); if (content.length >= MINIMUM_CHUNK_SIZE_BYTES) throw new IllegalArgumentException("String must be less than " + MINIMUM_CHUNK_SIZE_BYTES + " bytes."); String contentMD5 = null; try { contentMD5 = MD5ChecksumHelper.getMD5ChecksumForByteArray(content); } catch (IOException e) { throw new SynapseClientException(e); } CreateChunkedFileTokenRequest ccftr = new CreateChunkedFileTokenRequest(); ccftr.setFileName("content"); ccftr.setContentType(contentType.toString()); ccftr.setContentMD5(contentMD5); ccftr.setUploadDestination(uploadDestination); ccftr.setStorageLocationId(uploadDestination == null ? null : uploadDestination.getStorageLocationId()); // Start the upload ChunkedFileToken token = createChunkedFileUploadToken(ccftr); // because of the restriction on string length there will be exactly one // chunk List<Long> chunkNumbers = new ArrayList<Long>(); long currentChunkNumber = 1; chunkNumbers.add(currentChunkNumber); ChunkRequest request = new ChunkRequest(); request.setChunkedFileToken(token); request.setChunkNumber((long) currentChunkNumber); URL presignedURL = createChunkedPresignedUrl(request); getHttpClientHelper().putBytesToURL(presignedURL, content, contentType.toString()); CompleteAllChunksRequest cacr = new CompleteAllChunksRequest(); cacr.setChunkedFileToken(token); cacr.setChunkNumbers(chunkNumbers); UploadDaemonStatus status = startUploadDeamon(cacr); State state = status.getState(); if (state.equals(State.FAILED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); long backOffMillis = 100L; // initially just 1/10 sec, but will // exponentially increase while (state.equals(State.PROCESSING) && backOffMillis <= MAX_BACKOFF_MILLIS) { try { Thread.sleep(backOffMillis); } catch (InterruptedException e) { // continue } status = getCompleteUploadDaemonStatus(status.getDaemonId()); state = status.getState(); if (state.equals(State.FAILED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); backOffMillis *= 2; // exponential backoff } if (!state.equals(State.COMPLETED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); return status.getFileHandleId(); } private static final ContentType STRING_MESSAGE_CONTENT_TYPE = ContentType .create("text/plain", MESSAGE_CHARSET); /** * Convenience function to upload a simple string message body, then send * message using resultant fileHandleId * * @param message * @param messageBody * @return the created message * @throws SynapseException */ @Override public MessageToUser sendStringMessage(MessageToUser message, String messageBody) throws SynapseException { String fileHandleId = uploadToFileHandle( messageBody.getBytes(MESSAGE_CHARSET), STRING_MESSAGE_CONTENT_TYPE); message.setFileHandleId(fileHandleId); return sendMessage(message); } /** * Convenience function to upload a simple string message body, then send * message to entity owner using resultant fileHandleId * * @param message * @param entityId * @param messageBody * @return the created message * @throws SynapseException */ @Override public MessageToUser sendStringMessage(MessageToUser message, String entityId, String messageBody) throws SynapseException { String fileHandleId = uploadToFileHandle( messageBody.getBytes(MESSAGE_CHARSET), STRING_MESSAGE_CONTENT_TYPE); message.setFileHandleId(fileHandleId); return sendMessage(message, entityId); } @Override public MessageToUser sendMessage(MessageToUser message, String entityId) throws SynapseException { String uri = ENTITY + "/" + entityId + "/" + MESSAGE; try { String jsonBody = EntityFactory.createJSONStringForEntity(message); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageBundle> getInbox( List<MessageStatusType> inboxFilter, MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE_INBOX, inboxFilter, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageBundle> messages = new PaginatedResults<MessageBundle>( MessageBundle.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageToUser> getOutbox(MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE_OUTBOX, null, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageToUser> messages = new PaginatedResults<MessageToUser>( MessageToUser.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MessageToUser getMessage(String messageId) throws SynapseException { String uri = MESSAGE + "/" + messageId; try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MessageToUser forwardMessage(String messageId, MessageRecipientSet recipients) throws SynapseException { String uri = MESSAGE + "/" + messageId + FORWARD; try { String jsonBody = EntityFactory .createJSONStringForEntity(recipients); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageToUser> getConversation( String associatedMessageId, MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE + "/" + associatedMessageId + CONVERSATION, null, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageToUser> messages = new PaginatedResults<MessageToUser>( MessageToUser.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateMessageStatus(MessageStatus status) throws SynapseException { String uri = MESSAGE_STATUS; try { String jsonBody = EntityFactory.createJSONStringForEntity(status); getSharedClientConnection().putJson(repoEndpoint, uri, jsonBody, getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMessage(String messageId) throws SynapseException { String uri = MESSAGE + "/" + messageId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } private static String createDownloadMessageURI(String messageId, boolean redirect) { return MESSAGE + "/" + messageId + FILE + "?" + REDIRECT_PARAMETER + redirect; } @Override public String getMessageTemporaryUrl(String messageId) throws SynapseException, MalformedURLException, IOException { String uri = createDownloadMessageURI(messageId, false); return getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent()); } @Override public String downloadMessage(String messageId) throws SynapseException, MalformedURLException, IOException { String uri = createDownloadMessageURI(messageId, true); return getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent()); } @Override public void downloadMessageToFile(String messageId, File target) throws SynapseException { String uri = createDownloadMessageURI(messageId, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Get the child count for this entity * * @param entityId * @return * @throws SynapseException * @throws JSONException */ @Override public Long getChildCount(String entityId) throws SynapseException { String queryString = SELECT_ID_FROM_ENTITY_WHERE_PARENT_ID + entityId + LIMIT_1_OFFSET_1; JSONObject query = query(queryString); if (!query.has(TOTAL_NUM_RESULTS)) { throw new SynapseClientException("Query results did not have " + TOTAL_NUM_RESULTS); } try { return query.getLong(TOTAL_NUM_RESULTS); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Get the appropriate piece of the URL based on the attachment type * * @param type * @return */ public static String getAttachmentTypeURL( ServiceConstants.AttachmentType type) { if (type == AttachmentType.ENTITY) return ENTITY; else if (type == AttachmentType.USER_PROFILE) return USER_PROFILE_PATH; else throw new IllegalArgumentException("Unrecognized attachment type: " + type); } /** * Get the ids of all users and groups. * * @param client * @return * @throws SynapseException */ @Override public Set<String> getAllUserAndGroupIds() throws SynapseException { HashSet<String> ids = new HashSet<String>(); // Get all the users PaginatedResults<UserProfile> pr = this.getUsers(0, Integer.MAX_VALUE); for (UserProfile up : pr.getResults()) { ids.add(up.getOwnerId()); } PaginatedResults<UserGroup> groupPr = this.getGroups(0, Integer.MAX_VALUE); for (UserGroup ug : groupPr.getResults()) { ids.add(ug.getId()); } return ids; } /** * @return version * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public SynapseVersionInfo getVersionInfo() throws SynapseException, JSONObjectAdapterException { JSONObject json = getEntity(VERSION_INFO); return EntityFactory.createEntityFromJSONObject(json, SynapseVersionInfo.class); } /** * Get the activity generatedBy an Entity * * @param entityId * @return * @throws SynapseException */ @Override public Activity getActivityForEntity(String entityId) throws SynapseException { return getActivityForEntityVersion(entityId, null); } /** * Get the activity generatedBy an Entity * * @param entityId * @param versionNumber * @return * @throws SynapseException */ @Override public Activity getActivityForEntityVersion(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = createEntityUri(ENTITY_URI_PATH, entityId); if (versionNumber != null) { url += REPO_SUFFIX_VERSION + "/" + versionNumber; } url += GENERATED_BY_SUFFIX; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Activity(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Set the activity generatedBy an Entity * * @param entityId * @param activityId * @return * @throws SynapseException */ @Override public Activity setActivityForEntity(String entityId, String activityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ENTITY_URI_PATH, entityId) + GENERATED_BY_SUFFIX; if (activityId != null) url += "?" + PARAM_GENERATED_BY + "=" + activityId; try { JSONObject jsonObject = new JSONObject(); // no need for a body jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); return new Activity(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Delete the generatedBy relationship for an Entity (does not delete the * activity) * * @param entityId * @throws SynapseException */ @Override public void deleteGeneratedByForEntity(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String uri = createEntityUri(ENTITY_URI_PATH, entityId) + GENERATED_BY_SUFFIX; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Create an activity * * @param activity * @return * @throws SynapseException */ @Override public Activity createActivity(Activity activity) throws SynapseException { if (activity == null) throw new IllegalArgumentException("Activity can not be null"); String url = ACTIVITY_URI_PATH; JSONObjectAdapter toCreateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(activity.writeToJSONObject(toCreateAdapter) .toJSONString()); JSONObject jsonObj = createJSONObject(url, obj); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Activity(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get activity by id * * @param activityId * @return * @throws SynapseException */ @Override public Activity getActivity(String activityId) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activityId); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Activity(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Update an activity * * @param activity * @return * @throws SynapseException */ @Override public Activity putActivity(Activity activity) throws SynapseException { if (activity == null) throw new IllegalArgumentException("Activity can not be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activity.getId()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(activity.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Activity(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Delete an activity. This will remove all generatedBy connections to this * activity as well. * * @param activityId * @throws SynapseException */ @Override public void deleteActivity(String activityId) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String uri = createEntityUri(ACTIVITY_URI_PATH, activityId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public PaginatedResults<Reference> getEntitiesGeneratedBy( String activityId, Integer limit, Integer offset) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activityId + GENERATED_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Reference> results = new PaginatedResults<Reference>( Reference.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation createEvaluation(Evaluation eval) throws SynapseException { String uri = EVALUATION_URI_PATH; try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(eval); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Evaluation.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation getEvaluation(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = createEntityUri(EVALUATION_URI_PATH, evalId); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Evaluation(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public PaginatedResults<Evaluation> getEvaluationByContentSource(String id, int offset, int limit) throws SynapseException { String url = ENTITY_URI_PATH + "/" + id + EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public PaginatedResults<Evaluation> getEvaluationsPaginated(int offset, int limit) throws SynapseException { String url = EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Evaluation> getAvailableEvaluationsPaginated( int offset, int limit) throws SynapseException { String url = AVAILABLE_EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private String idsToString(List<String> ids) { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String s : ids) { if (firsttime) { firsttime = false; } else { sb.append(","); } sb.append(s); } return sb.toString(); } @Override public PaginatedResults<Evaluation> getAvailableEvaluationsPaginated( int offset, int limit, List<String> evaluationIds) throws SynapseException { String url = AVAILABLE_EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit + "&" + EVALUATION_IDS_FILTER_PARAM + "=" + idsToString(evaluationIds); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation findEvaluation(String name) throws SynapseException, UnsupportedEncodingException { if (name == null) throw new IllegalArgumentException("Evaluation name cannot be null"); String encodedName = URLEncoder.encode(name, "UTF-8"); String url = EVALUATION_URI_PATH + "/" + NAME + "/" + encodedName; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Evaluation(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public Evaluation updateEvaluation(Evaluation eval) throws SynapseException { if (eval == null) throw new IllegalArgumentException("Evaluation can not be null"); String url = createEntityUri(EVALUATION_URI_PATH, eval.getId()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(eval.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Evaluation(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteEvaluation(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String uri = createEntityUri(EVALUATION_URI_PATH, evalId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public Submission createIndividualSubmission(Submission sub, String etag, String challengeEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { if (etag==null) throw new IllegalArgumentException("etag is required."); if (sub.getTeamId()!=null) throw new IllegalArgumentException("For an individual submission Team ID must be null."); if (sub.getContributors()!=null && !sub.getContributors().isEmpty()) throw new IllegalArgumentException("For an individual submission, contributors may not be specified."); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "?" + ETAG + "=" + etag; if (challengeEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "&" + CHALLENGE_ENDPOINT_PARAM + "=" + urlEncode(challengeEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(sub); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Submission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public TeamSubmissionEligibility getTeamSubmissionEligibility(String evaluationId, String teamId) throws SynapseException { if (evaluationId==null) throw new IllegalArgumentException("evaluationId is required."); if (teamId==null) throw new IllegalArgumentException("teamId is required."); String url = EVALUATION_URI_PATH+"/"+evaluationId+TEAM+"/"+teamId+ SUBMISSION_ELIGIBILITY; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new TeamSubmissionEligibility(adapter); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public Submission createTeamSubmission(Submission sub, String etag, String submissionEligibilityHash, String challengeEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { if (etag==null) throw new IllegalArgumentException("etag is required."); if (submissionEligibilityHash==null) throw new IllegalArgumentException("For a Team submission 'submissionEligibilityHash' is required."); if (sub.getTeamId()==null) throw new IllegalArgumentException("For a Team submission Team ID is required."); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "?" + ETAG + "=" + etag + "&" + SUBMISSION_ELIGIBILITY_HASH+"="+submissionEligibilityHash; if (challengeEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "&" + CHALLENGE_ENDPOINT_PARAM + "=" + urlEncode(challengeEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(sub); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Submission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Add a contributor to an existing submission. This is available to Synapse administrators only. * @param submissionId * @param contributor * @return */ public SubmissionContributor addSubmissionContributor(String submissionId, SubmissionContributor contributor) throws SynapseException { validateStringAsLong(submissionId); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + "/contributor"; try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(contributor); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, SubmissionContributor.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Submission getSubmission(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Submission(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public SubmissionStatus getSubmissionStatus(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Submission id cannot be null"); String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId + "/" + STATUS; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new SubmissionStatus(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public SubmissionStatus updateSubmissionStatus(SubmissionStatus status) throws SynapseException { if (status == null) { throw new IllegalArgumentException( "SubmissionStatus cannot be null."); } if (status.getAnnotations() != null) { AnnotationsUtils.validateAnnotations(status.getAnnotations()); } String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + status.getId() + STATUS; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(status.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new SubmissionStatus(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } public BatchUploadResponse updateSubmissionStatusBatch(String evaluationId, SubmissionStatusBatch batch) throws SynapseException { if (evaluationId == null) { throw new IllegalArgumentException("evaluationId is required."); } if (batch == null) { throw new IllegalArgumentException( "SubmissionStatusBatch cannot be null."); } if (batch.getIsFirstBatch() == null) { throw new IllegalArgumentException( "isFirstBatch must be set to true or false."); } if (batch.getIsLastBatch() == null) { throw new IllegalArgumentException( "isLastBatch must be set to true or false."); } if (!batch.getIsFirstBatch() && batch.getBatchToken() == null) { throw new IllegalArgumentException( "batchToken cannot be null for any but the first batch."); } List<SubmissionStatus> statuses = batch.getStatuses(); if (statuses == null || statuses.size() == 0) { throw new IllegalArgumentException( "SubmissionStatusBatch must contain at least one SubmissionStatus."); } for (SubmissionStatus status : statuses) { if (status.getAnnotations() != null) { AnnotationsUtils.validateAnnotations(status.getAnnotations()); } } String url = EVALUATION_URI_PATH + "/" + evaluationId + STATUS_BATCH; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(batch.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new BatchUploadResponse(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteSubmission(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Submission id cannot be null"); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public PaginatedResults<Submission> getAllSubmissions(String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionStatus> getAllSubmissionStatuses( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_STATUS_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionStatus> results = new PaginatedResults<SubmissionStatus>( SubmissionStatus.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getAllSubmissionBundles( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Submission> getAllSubmissionsByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionStatus> getAllSubmissionStatusesByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_STATUS_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionStatus> results = new PaginatedResults<SubmissionStatus>( SubmissionStatus.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getAllSubmissionBundlesByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Submission> getMySubmissions(String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getMySubmissionBundles( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get a temporary URL to access a File contained in a Submission. * * @param submissionId * @param fileHandleId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileTemporaryUrlForSubmissionFileHandle(String submissionId, String fileHandleId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + FILE + "/" + fileHandleId + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(url); } @Override public void downloadFromSubmission(String submissionId, String fileHandleId, File destinationFile) throws SynapseException { String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + FILE + "/" + fileHandleId; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } @Override public Long getSubmissionCount(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); PaginatedResults<Submission> res = getAllSubmissions(evalId, 0, 0); return res.getTotalNumberOfResults(); } /** * Execute a user query over the Submissions of a specified Evaluation. * * @param query * @return * @throws SynapseException */ @Override public QueryTableResults queryEvaluation(String query) throws SynapseException { try { if (null == query) { throw new IllegalArgumentException("must provide a query"); } String queryUri; queryUri = EVALUATION_QUERY_URI_PATH + URLEncoder.encode(query, "UTF-8"); JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, queryUri, getUserAgent()); JSONObjectAdapter joa = new JSONObjectAdapterImpl(jsonObj); return new QueryTableResults(joa); } catch (Exception e) { throw new SynapseClientException(e); } } /** * Moves an entity and its descendants to the trash can. * * @param entityId * The ID of the entity to be moved to the trash can */ @Override public void moveToTrash(String entityId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_TRASH + "/" + entityId; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Moves an entity and its descendants out of the trash can. The entity will * be restored to the specified parent. If the parent is not specified, it * will be restored to the original parent. */ @Override public void restoreFromTrash(String entityId, String newParentId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_RESTORE + "/" + entityId; if (newParentId != null && !newParentId.isEmpty()) { url = url + "/" + newParentId; } getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Retrieves entities (in the trash can) deleted by the user. */ @Override public PaginatedResults<TrashedEntity> viewTrashForUser(long offset, long limit) throws SynapseException { String url = TRASHCAN_VIEW + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TrashedEntity> results = new PaginatedResults<TrashedEntity>( TrashedEntity.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Purges the specified entity from the trash can. After purging, the entity * will be permanently deleted. */ @Override public void purgeTrashForUser(String entityId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_PURGE + "/" + entityId; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Purges the trash can for the user. All the entities in the trash will be * permanently deleted. */ @Override public void purgeTrashForUser() throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, TRASHCAN_PURGE, null, getUserAgent()); } @Override public void logError(LogEntry logEntry) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(logEntry); jsonObject = createJSONObject(LOG, jsonObject); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override @Deprecated public List<UploadDestination> getUploadDestinations(String parentEntityId) throws SynapseException { // Get the json for this entity as a list wrapper String url = ENTITY + "/" + parentEntityId + "/uploadDestinations"; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { return ListWrapper.unwrap(new JSONObjectAdapterImpl(json), UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends StorageLocationSetting> T createStorageLocationSetting(T storageLocation) throws SynapseException { try { JSONObject jsonObject = EntityFactory.createJSONObjectForEntity(storageLocation); jsonObject = getSharedClientConnection().postJson(repoEndpoint, STORAGE_LOCATION, jsonObject.toString(), getUserAgent(), null); return (T) createJsonObjectFromInterface(jsonObject, StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") @Override public <T extends StorageLocationSetting> T getMyStorageLocationSetting(Long storageLocationId) throws SynapseException { try { String url = STORAGE_LOCATION + "/" + storageLocationId; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent(), null); return (T) createJsonObjectFromInterface(jsonObject, StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<StorageLocationSetting> getMyStorageLocationSettings() throws SynapseException { try { String url = STORAGE_LOCATION; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent(), null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(jsonObject), StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UploadDestinationLocation[] getUploadDestinationLocations(String parentEntityId) throws SynapseException { // Get the json for this entity as a list wrapper String url = ENTITY + "/" + parentEntityId + "/uploadDestinationLocations"; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { List<UploadDestinationLocation> locations = ListWrapper.unwrap(new JSONObjectAdapterImpl(json), UploadDestinationLocation.class); return locations.toArray(new UploadDestinationLocation[locations.size()]); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public UploadDestination getUploadDestination(String parentEntityId, Long storageLocationId) throws SynapseException { try { String uri = ENTITY + "/" + parentEntityId + "/uploadDestination/" + storageLocationId; JSONObject jsonObject = getSharedClientConnection().getJson(fileEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UploadDestination getDefaultUploadDestination(String parentEntityId) throws SynapseException { try { String uri = ENTITY + "/" + parentEntityId + "/uploadDestination"; JSONObject jsonObject = getSharedClientConnection().getJson(fileEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ProjectSetting getProjectSetting(String projectId, ProjectSettingsType projectSettingsType) throws SynapseException { try { String uri = PROJECT_SETTINGS + "/" + projectId + "/type/" + projectSettingsType; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, ProjectSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ProjectSetting createProjectSetting(ProjectSetting projectSetting) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(projectSetting); jsonObject = getSharedClientConnection().postJson(repoEndpoint, PROJECT_SETTINGS, jsonObject.toString(), getUserAgent(), null); return createJsonObjectFromInterface(jsonObject, ProjectSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateProjectSetting(ProjectSetting projectSetting) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(projectSetting); getSharedClientConnection().putJson(repoEndpoint, PROJECT_SETTINGS, jsonObject.toString(), getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteProjectSetting(String projectSettingsId) throws SynapseException { String uri = PROJECT_SETTINGS + "/" + projectSettingsId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @SuppressWarnings("unchecked") private <T extends JSONEntity> T createJsonObjectFromInterface( JSONObject jsonObject, Class<T> expectedType) throws JSONObjectAdapterException { if (jsonObject == null) { return null; } JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); String concreteType = adapter.getString("concreteType"); try { JSONEntity obj = (JSONEntity) Class.forName(concreteType).newInstance(); obj.initializeFromJSONObject(adapter); return (T) obj; } catch (Exception e) { throw new RuntimeException(e); } } /** * Add the entity to this user's Favorites list * * @param entityId * @return * @throws SynapseException */ @Override public EntityHeader addFavorite(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String url = createEntityUri(FAVORITE_URI_PATH, entityId); JSONObject jsonObj = getSharedClientConnection().postUri(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new EntityHeader(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Remove the entity from this user's Favorites list * * @param entityId * @throws SynapseException */ @Override public void removeFavorite(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String uri = createEntityUri(FAVORITE_URI_PATH, entityId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Retrieve this user's Favorites list * * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<EntityHeader> getFavorites(Integer limit, Integer offset) throws SynapseException { String url = FAVORITE_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Retrieve this user's Projects list * * @param type the type of list to get * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getMyProjects(ProjectListType type, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(type, null, null, sortColumn, sortDirection, limit, offset); } /** * Retrieve a user's Projects list * * @param userId the user for which to get the project list * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getProjectsFromUser(Long userId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(ProjectListType.OTHER_USER_PROJECTS, userId, null, sortColumn, sortDirection, limit, offset); } /** * Retrieve a teams's Projects list * * @param teamId the team for which to get the project list * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getProjectsForTeam(Long teamId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(ProjectListType.TEAM_PROJECTS, null, teamId, sortColumn, sortDirection, limit, offset); } private PaginatedResults<ProjectHeader> getProjects(ProjectListType type, Long userId, Long teamId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException, SynapseClientException { String url = PROJECTS_URI_PATH + '/' + type.name(); if (userId != null) { url += USER + '/' + userId; } if (teamId != null) { url += TEAM + '/' + teamId; } if (sortColumn == null) { sortColumn = ProjectListSortColumn.LAST_ACTIVITY; } if (sortDirection == null) { sortDirection = SortDirection.DESC; } url += '?' + OFFSET_PARAMETER + offset + '&' + LIMIT_PARAMETER + limit + "&sort=" + sortColumn.name() + "&sortDirection=" + sortDirection.name(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<ProjectHeader> results = new PaginatedResults<ProjectHeader>(ProjectHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Creates a DOI for the specified entity. The DOI will always be associated * with the current version of the entity. */ @Override public void createEntityDoi(String entityId) throws SynapseException { createEntityDoi(entityId, null); } /** * Creates a DOI for the specified entity version. If version is null, the * DOI will always be associated with the current version of the entity. */ @Override public void createEntityDoi(String entityId, Long entityVersion) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide entity ID."); } String url = ENTITY + "/" + entityId; if (entityVersion != null) { url = url + REPO_SUFFIX_VERSION + "/" + entityVersion; } url = url + DOI; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Gets the DOI for the specified entity version. The DOI is for the current * version of the entity. */ @Override public Doi getEntityDoi(String entityId) throws SynapseException { return getEntityDoi(entityId, null); } /** * Gets the DOI for the specified entity version. If version is null, the * DOI is for the current version of the entity. */ @Override public Doi getEntityDoi(String entityId, Long entityVersion) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide entity ID."); } try { String url = ENTITY + "/" + entityId; if (entityVersion != null) { url = url + REPO_SUFFIX_VERSION + "/" + entityVersion; } url = url + DOI; JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Doi doi = new Doi(); doi.initializeFromJSONObject(adapter); return doi; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Gets the header information of entities whose file's MD5 matches the * given MD5 checksum. */ @Override public List<EntityHeader> getEntityHeaderByMd5(String md5) throws SynapseException { if (md5 == null || md5.isEmpty()) { throw new IllegalArgumentException( "Must provide a nonempty MD5 string."); } try { String url = ENTITY + "/md5/" + md5; JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); results.initializeFromJSONObject(adapter); return results.getResults(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public String retrieveApiKey() throws SynapseException { try { String url = "/secretKey"; JSONObject jsonObj = getSharedClientConnection().getJson( authEndpoint, url, getUserAgent()); SecretKey key = EntityFactory.createEntityFromJSONObject(jsonObj, SecretKey.class); return key.getSecretKey(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void invalidateApiKey() throws SynapseException { getSharedClientConnection().invalidateApiKey(getUserAgent()); } @Override public AccessControlList updateEvaluationAcl(AccessControlList acl) throws SynapseException { if (acl == null) { throw new IllegalArgumentException("ACL can not be null."); } String url = EVALUATION_ACL_URI_PATH; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(acl.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new AccessControlList(adapter); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getEvaluationAcl(String evalId) throws SynapseException { if (evalId == null) { throw new IllegalArgumentException("Evaluation ID cannot be null."); } String url = EVALUATION_URI_PATH + "/" + evalId + "/acl"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new AccessControlList(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UserEvaluationPermissions getUserEvaluationPermissions(String evalId) throws SynapseException { if (evalId == null) { throw new IllegalArgumentException("Evaluation ID cannot be null."); } String url = EVALUATION_URI_PATH + "/" + evalId + "/permissions"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new UserEvaluationPermissions(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public String appendRowSetToTableStart(AppendableRowSet rowSet, String tableId) throws SynapseException { AppendableRowSetRequest request = new AppendableRowSetRequest(); request.setEntityId(tableId); request.setToAppend(rowSet); return startAsynchJob(AsynchJobType.TableAppendRowSet, request); } @Override public RowReferenceSet appendRowSetToTableGet(String token, String tableId) throws SynapseException, SynapseResultNotReadyException { RowReferenceSetResults rrs = (RowReferenceSetResults) getAsyncResult( AsynchJobType.TableAppendRowSet, token, tableId); return rrs.getRowReferenceSet(); } @Override public String startTableTransactionJob(List<TableUpdateRequest> changes, String tableId) throws SynapseException { TableUpdateTransactionRequest request = new TableUpdateTransactionRequest(); request.setEntityId(tableId); request.setChanges(changes); return startAsynchJob(AsynchJobType.TableTransaction, request); } @Override public List<TableUpdateResponse> getTableTransactionJobResults(String token, String tableId) throws SynapseException, SynapseResultNotReadyException { TableUpdateTransactionResponse response = (TableUpdateTransactionResponse) getAsyncResult( AsynchJobType.TableTransaction, token, tableId); return response.getResults(); } @Override public RowReferenceSet appendRowsToTable(AppendableRowSet rowSet, long timeout, String tableId) throws SynapseException, InterruptedException { long start = System.currentTimeMillis(); // Start the job String jobId = appendRowSetToTableStart(rowSet, tableId); do { try { return appendRowSetToTableGet(jobId, tableId); } catch (SynapseResultNotReadyException e) { Thread.sleep(1000); } } while (System.currentTimeMillis() - start < timeout); // ran out of time. throw new SynapseClientException("Timed out waiting for jobId: " + jobId); } @Override public RowReferenceSet deleteRowsFromTable(RowSelection toDelete) throws SynapseException { if (toDelete == null) throw new IllegalArgumentException("RowSelection cannot be null"); if (toDelete.getTableId() == null) throw new IllegalArgumentException( "RowSelection.tableId cannot be null"); String uri = ENTITY + "/" + toDelete.getTableId() + TABLE + "/deleteRows"; try { String jsonBody = EntityFactory.createJSONStringForEntity(toDelete); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, RowReferenceSet.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public RowSet getRowsFromTable(RowReferenceSet toGet) throws SynapseException, SynapseTableUnavailableException { if (toGet == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); if (toGet.getTableId() == null) throw new IllegalArgumentException( "RowReferenceSet.tableId cannot be null"); String uri = ENTITY + "/" + toGet.getTableId() + TABLE + "/getRows"; try { String jsonBody = EntityFactory.createJSONStringForEntity(toGet); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, RowSet.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public TableFileHandleResults getFileHandlesFromTable( RowReferenceSet fileHandlesToFind) throws SynapseException { if (fileHandlesToFind == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); String uri = ENTITY + "/" + fileHandlesToFind.getTableId() + TABLE + FILE_HANDLES; return asymmetricalPost(getRepoEndpoint(), uri, fileHandlesToFind, TableFileHandleResults.class, null); } /** * Get the temporary URL for the data file of a file handle column for a * row. This is an alternative to downloading the file. * * @param entityId * @return * @throws IOException * @throws SynapseException */ @Override public URL getTableFileHandleTemporaryUrl(String tableId, RowReference row, String columnId) throws IOException, SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromTableFileHandleTemporaryUrl(String tableId, RowReference row, String columnId, File destinationFile) throws SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } @Override public URL getTableFileHandlePreviewTemporaryUrl(String tableId, RowReference row, String columnId) throws IOException, SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromTableFileHandlePreviewTemporaryUrl(String tableId, RowReference row, String columnId, File destinationFile) throws SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } private static String getUriForFileHandle(String tableId, RowReference row, String columnId) { return ENTITY + "/" + tableId + TABLE + COLUMN + "/" + columnId + ROW_ID + "/" + row.getRowId() + ROW_VERSION + "/" + row.getVersionNumber(); } @Override public String queryTableEntityBundleAsyncStart(String sql, Long offset, Long limit, boolean isConsistent, int partsMask, String tableId) throws SynapseException { Query query = new Query(); query.setSql(sql); query.setIsConsistent(isConsistent); query.setOffset(offset); query.setLimit(limit); QueryBundleRequest bundleRequest = new QueryBundleRequest(); bundleRequest.setEntityId(tableId); bundleRequest.setQuery(query); bundleRequest.setPartMask((long) partsMask); return startAsynchJob(AsynchJobType.TableQuery, bundleRequest); } @Override public QueryResultBundle queryTableEntityBundleAsyncGet( String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (QueryResultBundle) getAsyncResult(AsynchJobType.TableQuery, asyncJobToken, tableId); } @Override public String queryTableEntityNextPageAsyncStart(String nextPageToken, String tableId) throws SynapseException { QueryNextPageToken queryNextPageToken = new QueryNextPageToken(); queryNextPageToken.setEntityId(tableId); queryNextPageToken.setToken(nextPageToken); return startAsynchJob(AsynchJobType.TableQueryNextPage, queryNextPageToken); } @Override public QueryResult queryTableEntityNextPageAsyncGet(String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (QueryResult) getAsyncResult(AsynchJobType.TableQueryNextPage, asyncJobToken, tableId); } @Override public String downloadCsvFromTableAsyncStart(String sql, boolean writeHeader, boolean includeRowIdAndRowVersion, CsvTableDescriptor csvDescriptor, String tableId) throws SynapseException { DownloadFromTableRequest downloadRequest = new DownloadFromTableRequest(); downloadRequest.setEntityId(tableId); downloadRequest.setSql(sql); downloadRequest.setWriteHeader(writeHeader); downloadRequest.setIncludeRowIdAndRowVersion(includeRowIdAndRowVersion); downloadRequest.setCsvTableDescriptor(csvDescriptor); return startAsynchJob(AsynchJobType.TableCSVDownload, downloadRequest); } @Override public DownloadFromTableResult downloadCsvFromTableAsyncGet( String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (DownloadFromTableResult) getAsyncResult( AsynchJobType.TableCSVDownload, asyncJobToken, tableId); } @Override public String uploadCsvToTableAsyncStart(String tableId, String fileHandleId, String etag, Long linesToSkip, CsvTableDescriptor csvDescriptor) throws SynapseException { return uploadCsvToTableAsyncStart(tableId, fileHandleId, etag, linesToSkip, csvDescriptor, null); } @Override public String uploadCsvToTableAsyncStart(String tableId, String fileHandleId, String etag, Long linesToSkip, CsvTableDescriptor csvDescriptor, List<String> columnIds) throws SynapseException { UploadToTableRequest uploadRequest = new UploadToTableRequest(); uploadRequest.setTableId(tableId); uploadRequest.setUploadFileHandleId(fileHandleId); uploadRequest.setUpdateEtag(etag); uploadRequest.setLinesToSkip(linesToSkip); uploadRequest.setCsvTableDescriptor(csvDescriptor); uploadRequest.setColumnIds(columnIds); return startAsynchJob(AsynchJobType.TableCSVUpload, uploadRequest); } @Override public UploadToTableResult uploadCsvToTableAsyncGet(String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (UploadToTableResult) getAsyncResult( AsynchJobType.TableCSVUpload, asyncJobToken, tableId); } @Override public String uploadCsvTablePreviewAsyncStart(UploadToTablePreviewRequest request) throws SynapseException { return startAsynchJob(AsynchJobType.TableCSVUploadPreview, request); } @Override public UploadToTablePreviewResult uploadCsvToTablePreviewAsyncGet(String asyncJobToken) throws SynapseException, SynapseResultNotReadyException { String entityId = null; return (UploadToTablePreviewResult) getAsyncResult( AsynchJobType.TableCSVUploadPreview, asyncJobToken, entityId); } @Override public ColumnModel createColumnModel(ColumnModel model) throws SynapseException { if (model == null) throw new IllegalArgumentException("ColumnModel cannot be null"); String url = COLUMN; return createJSONEntity(url, model); } @Override public List<ColumnModel> createColumnModels(List<ColumnModel> models) throws SynapseException { if (models == null) { throw new IllegalArgumentException("ColumnModel cannot be null"); } String url = COLUMN_BATCH; List<ColumnModel> results = createJSONEntityFromListWrapper(url, ListWrapper.wrap(models, ColumnModel.class), ColumnModel.class); return results; } @Override public ColumnModel getColumnModel(String columnId) throws SynapseException { if (columnId == null) throw new IllegalArgumentException("ColumnId cannot be null"); String url = COLUMN + "/" + columnId; try { return getJSONEntity(url, ColumnModel.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<ColumnModel> getColumnModelsForTableEntity(String tableEntityId) throws SynapseException { if (tableEntityId == null) throw new IllegalArgumentException("tableEntityId cannot be null"); String url = ENTITY + "/" + tableEntityId + COLUMN; try { PaginatedColumnModels pcm = getJSONEntity(url, PaginatedColumnModels.class); return pcm.getResults(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<ColumnModel> getDefaultColumnsForView(ViewType viewType) throws SynapseException { if(viewType == null){ throw new IllegalArgumentException("Viewtype cannot be null"); } try { String url = COLUMN_VIEW_DEFAULT+viewType.name(); JSONObject jsonObject = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); return ListWrapper.unwrap(new JSONObjectAdapterImpl(jsonObject), ColumnModel.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedColumnModels listColumnModels(String prefix, Long limit, Long offset) throws SynapseException { String url = buildListColumnModelUrl(prefix, limit, offset); try { return getJSONEntity(url, PaginatedColumnModels.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Build up the URL for listing all ColumnModels * * @param prefix * @param limit * @param offset * @return */ static String buildListColumnModelUrl(String prefix, Long limit, Long offset) { StringBuilder builder = new StringBuilder(); builder.append(COLUMN); int count = 0; if (prefix != null || limit != null || offset != null) { builder.append("?"); } if (prefix != null) { builder.append("prefix="); builder.append(prefix); count++; } if (limit != null) { if (count > 0) { builder.append("&"); } builder.append("limit="); builder.append(limit); count++; } if (offset != null) { if (count > 0) { builder.append("&"); } builder.append("offset="); builder.append(offset); } return builder.toString(); } /** * Start a new Asynchronous Job * * @param jobBody * @return * @throws SynapseException */ @Override public AsynchronousJobStatus startAsynchronousJob( AsynchronousRequestBody jobBody) throws SynapseException { if (jobBody == null) throw new IllegalArgumentException("JobBody cannot be null"); String url = ASYNCHRONOUS_JOB; return asymmetricalPost(getRepoEndpoint(), url, jobBody, AsynchronousJobStatus.class, null); } /** * Get the status of an Asynchronous Job from its ID. * * @param jobId * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public AsynchronousJobStatus getAsynchronousJobStatus(String jobId) throws JSONObjectAdapterException, SynapseException { if (jobId == null) throw new IllegalArgumentException("JobId cannot be null"); String url = ASYNCHRONOUS_JOB + "/" + jobId; return getJSONEntity(url, AsynchronousJobStatus.class); } @Override public Team createTeam(Team team) throws SynapseException { try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(team); jsonObj = createJSONObject(TEAM, jsonObj); return initializeFromJSONObject(jsonObj, Team.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Team getTeam(String id) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + id); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Team results = new Team(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Team> getTeams(String fragment, long limit, long offset) throws SynapseException { String uri = null; if (fragment == null) { uri = TEAMS + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAMS + "?" + NAME_FRAGMENT_FILTER + "=" + urlEncode(fragment) + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Team> results = new PaginatedResults<Team>(Team.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<Team> listTeams(List<Long> ids) throws SynapseException { try { IdList idList = new IdList(); idList.setList(ids); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), TEAM_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), Team.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Team> getTeamsForUser(String memberId, long limit, long offset) throws SynapseException { String uri = USER + "/" + memberId + TEAM + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Team> results = new PaginatedResults<Team>(Team.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static String createGetTeamIconURI(String teamId, boolean redirect) { return TEAM + "/" + teamId + ICON + "?" + REDIRECT_PARAMETER + redirect; } @Override public URL getTeamIcon(String teamId) throws SynapseException { try { return getUrl(createGetTeamIconURI(teamId, false)); } catch (IOException e) { throw new SynapseClientException(e); } } // alternative to getTeamIcon @Override public void downloadTeamIcon(String teamId, File target) throws SynapseException { String uri = createGetTeamIconURI(teamId, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } @Override public Team updateTeam(Team team) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(team.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, TEAM, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Team(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteTeam(String teamId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, TEAM + "/" + teamId, getUserAgent()); } @Override public void addTeamMember(String teamId, String memberId, String teamEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = TEAM + "/" + teamId + MEMBER + "/" + memberId; if (teamEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + TEAM_ENDPOINT_PARAM + "=" + urlEncode(teamEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } getSharedClientConnection().putJson(repoEndpoint, uri, new JSONObject().toString(), getUserAgent()); } @Override public ResponseMessage addTeamMember(JoinTeamSignedToken joinTeamSignedToken, String teamEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = TEAM + "Member"; if (teamEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + TEAM_ENDPOINT_PARAM + "=" + urlEncode(teamEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } return asymmetricalPut(getRepoEndpoint(), uri, joinTeamSignedToken, ResponseMessage.class); } private static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<TeamMember> getTeamMembers(String teamId, String fragment, long limit, long offset) throws SynapseException { String uri = null; if (fragment == null) { uri = TEAM_MEMBERS + "/" + teamId + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM_MEMBERS + "/" + teamId + "?" + NAME_FRAGMENT_FILTER + "=" + urlEncode(fragment) + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TeamMember> results = new PaginatedResults<TeamMember>( TeamMember.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<TeamMember> listTeamMembers(String teamId, List<Long> ids) throws SynapseException { try { IdList idList = new IdList(); idList.setList(ids); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), TEAM+"/"+teamId+MEMBER_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), TeamMember.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<TeamMember> listTeamMembers(List<Long> teamIds, String userId) throws SynapseException { try { IdList idList = new IdList(); idList.setList(teamIds); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), USER+"/"+userId+MEMBER_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), TeamMember.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public TeamMember getTeamMember(String teamId, String memberId) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + teamId + MEMBER + "/" + memberId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); TeamMember result = new TeamMember(); try { result.initializeFromJSONObject(adapter); return result; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void removeTeamMember(String teamId, String memberId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, TEAM + "/" + teamId + MEMBER + "/" + memberId, getUserAgent()); } @Override public void setTeamMemberPermissions(String teamId, String memberId, boolean isAdmin) throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, TEAM + "/" + teamId + MEMBER + "/" + memberId + PERMISSION + "?" + TEAM_MEMBERSHIP_PERMISSION + "=" + isAdmin, "", getUserAgent()); } @Override public TeamMembershipStatus getTeamMembershipStatus(String teamId, String principalId) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + teamId + MEMBER + "/" + principalId + MEMBERSHIP_STATUS); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); TeamMembershipStatus results = new TeamMembershipStatus(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getTeamACL(String teamId) throws SynapseException { if (teamId == null) { throw new IllegalArgumentException("Team ID cannot be null."); } String url = TEAM + "/" + teamId + "/acl"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new AccessControlList(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList updateTeamACL(AccessControlList acl) throws SynapseException { if (acl == null) { throw new IllegalArgumentException("ACL can not be null."); } String url = TEAM+"/acl"; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(acl.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new AccessControlList(adapter); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipInvtnSubmission createMembershipInvitation( MembershipInvtnSubmission invitation, String acceptInvitationEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { try { JSONObject jsonObj = EntityFactory .createJSONObjectForEntity(invitation); String uri = MEMBERSHIP_INVITATION; if (acceptInvitationEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + ACCEPT_INVITATION_ENDPOINT_PARAM + "=" + urlEncode(acceptInvitationEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, MembershipInvtnSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipInvtnSubmission getMembershipInvitation(String invitationId) throws SynapseException { JSONObject jsonObj = getEntity(MEMBERSHIP_INVITATION + "/" + invitationId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MembershipInvtnSubmission results = new MembershipInvtnSubmission(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipInvitation> getOpenMembershipInvitations( String memberId, String teamId, long limit, long offset) throws SynapseException { String uri = null; if (teamId == null) { uri = USER + "/" + memberId + OPEN_MEMBERSHIP_INVITATION + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = USER + "/" + memberId + OPEN_MEMBERSHIP_INVITATION + "?" + TEAM_ID_REQUEST_PARAMETER + "=" + teamId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipInvitation> results = new PaginatedResults<MembershipInvitation>( MembershipInvitation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipInvtnSubmission> getOpenMembershipInvitationSubmissions( String teamId, String inviteeId, long limit, long offset) throws SynapseException { String uri = null; if (inviteeId == null) { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_INVITATION + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_INVITATION + "?" + INVITEE_ID_REQUEST_PARAMETER + "=" + inviteeId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipInvtnSubmission> results = new PaginatedResults<MembershipInvtnSubmission>( MembershipInvtnSubmission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMembershipInvitation(String invitationId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, MEMBERSHIP_INVITATION + "/" + invitationId, getUserAgent()); } @Override public MembershipRqstSubmission createMembershipRequest( MembershipRqstSubmission request, String acceptRequestEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { try { String uri = MEMBERSHIP_REQUEST; if (acceptRequestEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + ACCEPT_REQUEST_ENDPOINT_PARAM + "=" + urlEncode(acceptRequestEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(request); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, MembershipRqstSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipRqstSubmission getMembershipRequest(String requestId) throws SynapseException { JSONObject jsonObj = getEntity(MEMBERSHIP_REQUEST + "/" + requestId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MembershipRqstSubmission results = new MembershipRqstSubmission(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipRequest> getOpenMembershipRequests( String teamId, String requestorId, long limit, long offset) throws SynapseException { String uri = null; if (requestorId == null) { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_REQUEST + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_REQUEST + "?" + REQUESTOR_ID_REQUEST_PARAMETER + "=" + requestorId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipRequest> results = new PaginatedResults<MembershipRequest>( MembershipRequest.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipRqstSubmission> getOpenMembershipRequestSubmissions( String requesterId, String teamId, long limit, long offset) throws SynapseException { String uri = null; if (teamId == null) { uri = USER + "/" + requesterId + OPEN_MEMBERSHIP_REQUEST + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = USER + "/" + requesterId + OPEN_MEMBERSHIP_REQUEST + "?" + TEAM_ID_REQUEST_PARAMETER + "=" + teamId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipRqstSubmission> results = new PaginatedResults<MembershipRqstSubmission>( MembershipRqstSubmission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMembershipRequest(String requestId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, MEMBERSHIP_REQUEST + "/" + requestId, getUserAgent()); } @Override public void createUser(NewUser user) throws SynapseException { try { JSONObject obj = EntityFactory.createJSONObjectForEntity(user); getSharedClientConnection().postJson(authEndpoint, "/user", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void sendPasswordResetEmail(String email) throws SynapseException { try { Username user = new Username(); user.setEmail(email); JSONObject obj = EntityFactory.createJSONObjectForEntity(user); getSharedClientConnection().postJson(authEndpoint, "/user/password/email", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void changePassword(String sessionToken, String newPassword) throws SynapseException { try { ChangePasswordRequest change = new ChangePasswordRequest(); change.setSessionToken(sessionToken); change.setPassword(newPassword); JSONObject obj = EntityFactory.createJSONObjectForEntity(change); getSharedClientConnection().postJson(authEndpoint, "/user/password", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void signTermsOfUse(String sessionToken, boolean acceptTerms) throws SynapseException { signTermsOfUse(sessionToken, DomainType.SYNAPSE, acceptTerms); } @Override public void signTermsOfUse(String sessionToken, DomainType domain, boolean acceptTerms) throws SynapseException { try { Session session = new Session(); session.setSessionToken(sessionToken); session.setAcceptsTermsOfUse(acceptTerms); Map<String, String> parameters = domainToParameterMap(domain); JSONObject obj = EntityFactory.createJSONObjectForEntity(session); getSharedClientConnection().postJson(authEndpoint, "/termsOfUse", obj.toString(), getUserAgent(), parameters); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString) throws SynapseException { return passThroughOpenIDParameters(queryString, false); } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString, Boolean createUserIfNecessary) throws SynapseException { return passThroughOpenIDParameters(queryString, createUserIfNecessary, DomainType.SYNAPSE); } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString, Boolean createUserIfNecessary, DomainType domain) throws SynapseException { try { URIBuilder builder = new URIBuilder(); builder.setPath("/openIdCallback"); builder.setQuery(queryString); builder.setParameter("org.sagebionetworks.createUserIfNecessary", createUserIfNecessary.toString()); Map<String, String> parameters = domainToParameterMap(domain); JSONObject session = getSharedClientConnection().postJson( authEndpoint, builder.toString(), "", getUserAgent(), parameters); return EntityFactory.createEntityFromJSONObject(session, Session.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getOAuth2AuthenticationUrl(org.sagebionetworks.repo.model.oauth.OAuthUrlRequest) */ @Override public OAuthUrlResponse getOAuth2AuthenticationUrl(OAuthUrlRequest request) throws SynapseException{ return asymmetricalPost(getAuthEndpoint(), AUTH_OAUTH_2_AUTH_URL, request, OAuthUrlResponse.class, null); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#validateOAuthAuthenticationCode(org.sagebionetworks.repo.model.oauth.OAuthValidationRequest) */ @Override public Session validateOAuthAuthenticationCode(OAuthValidationRequest request) throws SynapseException{ return asymmetricalPost(getAuthEndpoint(), AUTH_OAUTH_2_SESSION, request, Session.class, null); } @Override public PrincipalAlias bindOAuthProvidersUserId(OAuthValidationRequest request) throws SynapseException { return asymmetricalPost(authEndpoint, AUTH_OAUTH_2_ALIAS, request, PrincipalAlias.class, null); } @Override public void unbindOAuthProvidersUserId(OAuthProvider provider, String alias) throws SynapseException { if (provider==null) throw new IllegalArgumentException("provider is required."); if (alias==null) throw new IllegalArgumentException("alias is required."); try { getSharedClientConnection().deleteUri(authEndpoint, AUTH_OAUTH_2_ALIAS+"?provider="+ URLEncoder.encode(provider.name(), "UTF-8")+ "&"+"alias="+URLEncoder.encode(alias, "UTF-8"), getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } private Map<String, String> domainToParameterMap(DomainType domain) { Map<String, String> parameters = Maps.newHashMap(); parameters.put(AuthorizationConstants.DOMAIN_PARAM, domain.name()); return parameters; } @Override public Quiz getCertifiedUserTest() throws SynapseException { JSONObject jsonObj = getEntity(CERTIFIED_USER_TEST); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Quiz results = new Quiz(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PassingRecord submitCertifiedUserTestResponse(QuizResponse response) throws SynapseException { try { JSONObject jsonObj = EntityFactory .createJSONObjectForEntity(response); jsonObj = createJSONObject(CERTIFIED_USER_TEST_RESPONSE, jsonObj); return initializeFromJSONObject(jsonObj, PassingRecord.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void setCertifiedUserStatus(String principalId, boolean status) throws SynapseException { String url = USER + "/" + principalId + CERTIFIED_USER_STATUS + "?isCertified=" + status; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } @Override public PaginatedResults<QuizResponse> getCertifiedUserTestResponses( long offset, long limit, String principalId) throws SynapseException { String uri = null; if (principalId == null) { uri = CERTIFIED_USER_TEST_RESPONSE + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = CERTIFIED_USER_TEST_RESPONSE + "?" + PRINCIPAL_ID_REQUEST_PARAM + "=" + principalId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<QuizResponse> results = new PaginatedResults<QuizResponse>( QuizResponse.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteCertifiedUserTestResponse(String id) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, CERTIFIED_USER_TEST_RESPONSE + "/" + id, getUserAgent()); } @Override public PassingRecord getCertifiedUserPassingRecord(String principalId) throws SynapseException { if (principalId == null) throw new IllegalArgumentException("principalId may not be null."); JSONObject jsonObj = getEntity(USER + "/" + principalId + CERTIFIED_USER_PASSING_RECORD); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PassingRecord results = new PassingRecord(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<PassingRecord> getCertifiedUserPassingRecords( long offset, long limit, String principalId) throws SynapseException { if (principalId == null) throw new IllegalArgumentException("principalId may not be null."); String uri = USER + "/" + principalId + CERTIFIED_USER_PASSING_RECORDS + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<PassingRecord> results = new PaginatedResults<PassingRecord>( PassingRecord.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityQueryResults entityQuery(EntityQuery query) throws SynapseException { return asymmetricalPost(getRepoEndpoint(), QUERY, query, EntityQueryResults.class, null); } @Override public Challenge createChallenge(Challenge challenge) throws SynapseException { try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(challenge); jsonObj = createJSONObject(CHALLENGE, jsonObj); return initializeFromJSONObject(jsonObj, Challenge.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Returns the Challenge given its ID. Caller must * have READ permission on the associated Project. * * @param challengeId * @return * @throws SynapseException */ @Override public Challenge getChallenge(String challengeId) throws SynapseException { validateStringAsLong(challengeId); JSONObject jsonObj = getEntity(CHALLENGE+"/"+challengeId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Challenge results = new Challenge(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Challenge getChallengeForProject(String projectId) throws SynapseException { if (projectId==null) throw new IllegalArgumentException("projectId may not be null."); JSONObject jsonObj = getEntity(ENTITY+"/"+projectId+CHALLENGE); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Challenge results = new Challenge(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static final void validateStringAsLong(String s) throws SynapseClientException { if (s==null) throw new NullPointerException(); try { Long.parseLong(s); } catch (NumberFormatException e) { throw new SynapseClientException("Expected integer but found "+s, e); } } @Override public PaginatedIds listChallengeParticipants(String challengeId, Boolean affiliated, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+"/participant"; boolean anyParameters = false; if (affiliated!=null) { uri += "?affiliated="+affiliated; anyParameters = true; } if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengePagedResults listChallengesForParticipant(String participantPrincipalId, Long limit, Long offset) throws SynapseException { validateStringAsLong(participantPrincipalId); String uri = CHALLENGE+"?participantId="+participantPrincipalId; if (limit!=null) uri+= "&"+LIMIT+"="+limit; if (offset!=null) uri+="&"+OFFSET+"="+offset; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); ChallengePagedResults results = new ChallengePagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Challenge updateChallenge(Challenge challenge) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; String uri = CHALLENGE+"/"+challenge.getId(); try { obj = new JSONObject(challenge.writeToJSONObject(toUpdateAdapter).toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Challenge(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteChallenge(String id) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, CHALLENGE + "/" + id, getUserAgent()); } /** * Register a Team for a Challenge. The user making this request must be * registered for the Challenge and be an administrator of the Team. * * @param challengeId * @param teamId * @throws SynapseException */ @Override public ChallengeTeam createChallengeTeam(ChallengeTeam challengeTeam) throws SynapseException { try { if (challengeTeam.getChallengeId()==null) throw new IllegalArgumentException("challenge ID is required."); JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(challengeTeam); jsonObj = createJSONObject(CHALLENGE+"/"+challengeTeam.getChallengeId()+CHALLENGE_TEAM, jsonObj); return initializeFromJSONObject(jsonObj, ChallengeTeam.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengeTeamPagedResults listChallengeTeams(String challengeId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+CHALLENGE_TEAM; boolean anyParameters = false; if (limit!=null) { uri+= (anyParameters?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); ChallengeTeamPagedResults results = new ChallengeTeamPagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedIds listRegistratableTeams(String challengeId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+REGISTRATABLE_TEAM; boolean anyParameters = false; if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedIds listSubmissionTeams(String challengeId, String submitterPrincipalId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); validateStringAsLong(submitterPrincipalId); String uri = CHALLENGE+"/"+challengeId+SUBMISSION_TEAMS+"?submitterPrincipalId="+submitterPrincipalId; if (limit!=null) uri+= "&"+LIMIT+"="+limit; if (offset!=null) uri+="&"+OFFSET+"="+offset; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengeTeam updateChallengeTeam(ChallengeTeam challengeTeam) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; String challengeId = challengeTeam.getChallengeId(); if (challengeId==null) throw new IllegalArgumentException("challenge ID is required."); String challengeTeamId = challengeTeam.getId(); if (challengeTeamId==null) throw new IllegalArgumentException("ChallengeTeam ID is required."); String uri = CHALLENGE+"/"+challengeId+CHALLENGE_TEAM+"/"+challengeTeamId; try { obj = new JSONObject(challengeTeam.writeToJSONObject(toUpdateAdapter).toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new ChallengeTeam(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Remove a registered Team from a Challenge. * The user making this request must be registered for the Challenge and * be an administrator of the Team. * * @param challengeTeamId * @throws SynapseException */ @Override public void deleteChallengeTeam(String challengeTeamId) throws SynapseException { validateStringAsLong(challengeTeamId); getSharedClientConnection().deleteUri(repoEndpoint, CHALLENGE_TEAM + "/" + challengeTeamId, getUserAgent()); } public void addTeamToChallenge(String challengeId, String teamId) throws SynapseException { throw new RuntimeException("Not Yet Implemented"); } /** * Remove a registered Team from a Challenge. The user making this request * must be registered for the Challenge and be an administrator of the Team. * * @param challengeId * @param teamId * @throws SynapseException */ public void removeTeamFromChallenge(String challengeId, String teamId) throws SynapseException { throw new RuntimeException("Not Yet Implemented"); } @Override public VerificationSubmission createVerificationSubmission( VerificationSubmission verificationSubmission, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = VERIFICATION_SUBMISSION; if (notificationUnsubscribeEndpoint!=null) { uri += "?" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(verificationSubmission); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, VerificationSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public VerificationPagedResults listVerificationSubmissions( VerificationStateEnum currentState, Long submitterId, Long limit, Long offset) throws SynapseException { String uri = VERIFICATION_SUBMISSION; boolean anyParameters = false; if (currentState!=null) { uri+=(anyParameters ?"&":"?")+CURRENT_VERIFICATION_STATE+"="+currentState; anyParameters = true; } if (submitterId!=null) { uri+=(anyParameters ?"&":"?")+VERIFIED_USER_ID+"="+submitterId; anyParameters = true; } if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); VerificationPagedResults results = new VerificationPagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateVerificationState(long verificationId, VerificationState verificationState, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = VERIFICATION_SUBMISSION+"/"+verificationId+VERIFICATION_STATE; if (notificationUnsubscribeEndpoint!=null) { uri += "?" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(verificationState); createJSONObject(uri, jsonObj); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteVerificationSubmission(long verificationId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, VERIFICATION_SUBMISSION+"/"+verificationId, getUserAgent()); } @Override public UserBundle getMyOwnUserBundle(int mask) throws SynapseException { JSONObject jsonObj = getEntity(USER+USER_BUNDLE+"?mask="+mask); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserBundle results = new UserBundle(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UserBundle getUserBundle(long principalId, int mask) throws SynapseException { JSONObject jsonObj = getEntity(USER+"/"+principalId+USER_BUNDLE+"?mask="+mask); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserBundle results = new UserBundle(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static String createFileDownloadUri(FileHandleAssociation fileHandleAssociation, boolean redirect) { return FILE + "/" + fileHandleAssociation.getFileHandleId() + "?" + FILE_ASSOCIATE_TYPE + "=" + fileHandleAssociation.getAssociateObjectType() + "&" + FILE_ASSOCIATE_ID + "=" + fileHandleAssociation.getAssociateObjectId() + "&" + REDIRECT_PARAMETER + redirect; } @Override public URL getFileURL(FileHandleAssociation fileHandleAssociation) throws SynapseException { try { return getUrl(getFileEndpoint(), createFileDownloadUri(fileHandleAssociation, false)); } catch (IOException e) { throw new SynapseClientException(e); } } @Override public void downloadFile(FileHandleAssociation fileHandleAssociation, File target) throws SynapseException { String uri = createFileDownloadUri(fileHandleAssociation, true); getSharedClientConnection().downloadFromSynapse( getFileEndpoint() + uri, null, target, getUserAgent()); } @Override public Forum getForumByProjectId(String projectId) throws SynapseException { try { ValidateArgument.required(projectId, "projectId"); return getJSONEntity(PROJECT+"/"+projectId+FORUM, Forum.class); } catch (Exception e) { throw new SynapseClientException(e); } } @Override public Forum getForum(String forumId) throws SynapseException { try { ValidateArgument.required(forumId, "forumId"); return getJSONEntity(FORUM+"/"+forumId, Forum.class); } catch (Exception e) { throw new SynapseClientException(e); } } @Override public DiscussionThreadBundle createThread(CreateDiscussionThread toCreate) throws SynapseException { ValidateArgument.required(toCreate, "toCreate"); return asymmetricalPost(repoEndpoint, THREAD, toCreate, DiscussionThreadBundle.class, null); } @Override public DiscussionThreadBundle getThread(String threadId) throws SynapseException { try { ValidateArgument.required(threadId, "threadId"); String url = THREAD+"/"+threadId; return getJSONEntity(url, DiscussionThreadBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionThreadBundle> getThreadsForForum( String forumId, Long limit, Long offset, DiscussionThreadOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = FORUM+"/"+forumId+THREADS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter.toString(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionThreadBundle> results = new PaginatedResults<DiscussionThreadBundle>(DiscussionThreadBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public DiscussionThreadBundle updateThreadTitle(String threadId, UpdateThreadTitle newTitle) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(newTitle, "newTitle"); return asymmetricalPut(repoEndpoint, THREAD+"/"+threadId+THREAD_TITLE, newTitle, DiscussionThreadBundle.class); } @Override public DiscussionThreadBundle updateThreadMessage(String threadId, UpdateThreadMessage newMessage) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(newMessage, "newMessage"); return asymmetricalPut(repoEndpoint, THREAD+"/"+threadId+DISCUSSION_MESSAGE, newMessage, DiscussionThreadBundle.class); } @Override public void markThreadAsDeleted(String threadId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, THREAD+"/"+threadId, getUserAgent()); } @Override public void restoreDeletedThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+RESTORE, getUserAgent()); } @Override public DiscussionReplyBundle createReply(CreateDiscussionReply toCreate) throws SynapseException { ValidateArgument.required(toCreate, "toCreate"); return asymmetricalPost(repoEndpoint, REPLY, toCreate, DiscussionReplyBundle.class, null); } @Override public DiscussionReplyBundle getReply(String replyId) throws SynapseException { try { ValidateArgument.required(replyId, "replyId"); return getJSONEntity(REPLY+"/"+replyId, DiscussionReplyBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionReplyBundle> getRepliesForThread( String threadId, Long limit, Long offset, DiscussionReplyOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = THREAD+"/"+threadId+REPLIES +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionReplyBundle> results = new PaginatedResults<DiscussionReplyBundle>(DiscussionReplyBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public DiscussionReplyBundle updateReplyMessage(String replyId, UpdateReplyMessage newMessage) throws SynapseException { ValidateArgument.required(replyId, "replyId"); ValidateArgument.required(newMessage, "newMessage"); return asymmetricalPut(repoEndpoint, REPLY+"/"+replyId+DISCUSSION_MESSAGE, newMessage, DiscussionReplyBundle.class); } @Override public void markReplyAsDeleted(String replyId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, REPLY+"/"+replyId, getUserAgent()); } @Override public MultipartUploadStatus startMultipartUpload( MultipartUploadRequest request, Boolean forceRestart) throws SynapseException { ValidateArgument.required(request, "MultipartUploadRequest"); StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("/file/multipart"); //the restart parameter is optional. if(forceRestart != null){ pathBuilder.append("?forceRestart="); pathBuilder.append(forceRestart.toString()); } return asymmetricalPost(fileEndpoint, pathBuilder.toString(), request, MultipartUploadStatus.class, null); } @Override public BatchPresignedUploadUrlResponse getMultipartPresignedUrlBatch( BatchPresignedUploadUrlRequest request) throws SynapseException { ValidateArgument.required(request, "BatchPresignedUploadUrlRequest"); ValidateArgument.required(request.getUploadId(), "BatchPresignedUploadUrlRequest.uploadId"); String path = String.format("/file/multipart/%1$s/presigned/url/batch", request.getUploadId()); return asymmetricalPost(fileEndpoint,path,request, BatchPresignedUploadUrlResponse.class, null); } @Override public AddPartResponse addPartToMultipartUpload(String uploadId, int partNumber, String partMD5Hex) throws SynapseException { ValidateArgument.required(uploadId, "uploadId"); ValidateArgument.required(partMD5Hex, "partMD5Hex"); String path = String.format("/file/multipart/%1$s/add/%2$d?partMD5Hex=%3$s", uploadId, partNumber, partMD5Hex); return asymmetricalPut(fileEndpoint, path, null, AddPartResponse.class); } @Override public MultipartUploadStatus completeMultipartUpload(String uploadId) throws SynapseException { ValidateArgument.required(uploadId, "uploadId"); String path = String.format("/file/multipart/%1$s/complete", uploadId); return asymmetricalPut(fileEndpoint, path, null, MultipartUploadStatus.class); } @Override public S3FileHandle multipartUpload(InputStream input, long fileSize, String fileName, String contentType, Long storageLocationId, Boolean generatePreview, Boolean forceRestart) throws SynapseException { return new MultipartUpload(this, input, fileSize, fileName, contentType, storageLocationId, generatePreview, forceRestart, new TempFileProviderImpl()).uploadFile(); } @Override public S3FileHandle multipartUpload(File file, Long storageLocationId, Boolean generatePreview, Boolean forceRestart) throws SynapseException, IOException { InputStream fileInputStream = null; try{ fileInputStream = new FileInputStream(file); String fileName = file.getName(); long fileSize = file.length(); String contentType = guessContentTypeFromStream(file); return multipartUpload(fileInputStream, fileSize, fileName, contentType, storageLocationId, generatePreview, forceRestart); }finally{ IOUtils.closeQuietly(fileInputStream); } } @Override public URL getReplyUrl(String messageKey) throws SynapseException { try { ValidateArgument.required(messageKey, "messageKey"); return new URL(getJSONEntity(REPLY+URL+"?messageKey="+messageKey, MessageURL.class).getMessageUrl()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } catch (MalformedURLException e) { throw new SynapseClientException(e); } } @Override public URL getThreadUrl(String messageKey) throws SynapseException { try { ValidateArgument.required(messageKey, "messageKey"); return new URL(getJSONEntity(THREAD+URL+"?messageKey="+messageKey, MessageURL.class).getMessageUrl()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } catch (MalformedURLException e) { throw new SynapseClientException(e); } } @Override public Subscription subscribe(Topic toSubscribe) throws SynapseException { ValidateArgument.required(toSubscribe, "toSubscribe"); return asymmetricalPost(repoEndpoint, SUBSCRIPTION, toSubscribe, Subscription.class, null); } @Override public SubscriptionPagedResults getAllSubscriptions( SubscriptionObjectType objectType, Long limit, Long offset) throws SynapseException { try { ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(objectType, "objectType"); String url = SUBSCRIPTION+ALL+"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; url += "&"+OBJECT_TYPE_PARAM+"="+objectType.name(); return getJSONEntity(url, SubscriptionPagedResults.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public SubscriptionPagedResults listSubscriptions(SubscriptionRequest request) throws SynapseException { ValidateArgument.required(request, "request"); ValidateArgument.required(request.getObjectType(), "SubscriptionRequest.objectType"); ValidateArgument.required(request.getIdList(), "SubscriptionRequest.idList"); return asymmetricalPost(repoEndpoint, SUBSCRIPTION+LIST, request, SubscriptionPagedResults.class, null); } @Override public void unsubscribe(Long subscriptionId) throws SynapseException { ValidateArgument.required(subscriptionId, "subscriptionId"); getSharedClientConnection().deleteUri(repoEndpoint, SUBSCRIPTION+"/"+subscriptionId, getUserAgent()); } @Override public void unsubscribeAll() throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, SUBSCRIPTION+ALL, getUserAgent()); } @Override public Subscription getSubscription(String subscriptionId) throws SynapseException { try { ValidateArgument.required(subscriptionId, "subscriptionId"); return getJSONEntity(SUBSCRIPTION+"/"+subscriptionId, Subscription.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Etag getEtag(String objectId, ObjectType objectType) throws SynapseException { try { ValidateArgument.required(objectId, "objectId"); ValidateArgument.required(objectType, "objectType"); return getJSONEntity(OBJECT+"/"+objectId+"/"+objectType.name()+"/"+ETAG, Etag.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityId getEntityIdByAlias(String alias) throws SynapseException { ValidateArgument.required(alias, "alias"); try { return getJSONEntity(ENTITY+"/alias/"+alias, EntityId.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ThreadCount getThreadCountForForum(String forumId, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(filter, "filter"); String url = FORUM+"/"+forumId+THREAD_COUNT; url += "?filter="+filter; try { return getJSONEntity(url, ThreadCount.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ReplyCount getReplyCountForThread(String threadId, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(filter, "filter"); String url = THREAD+"/"+threadId+REPLY_COUNT; url += "?filter="+filter; try { return getJSONEntity(url, ReplyCount.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void pinThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+PIN, getUserAgent()); } @Override public void unpinThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+UNPIN, getUserAgent()); } @Override public PrincipalAliasResponse getPrincipalAlias(PrincipalAliasRequest request) throws SynapseException { return asymmetricalPost(repoEndpoint, PRINCIPAL+"/alias/", request, PrincipalAliasResponse.class, null); } @Override public void addDockerCommit(String entityId, DockerCommit dockerCommit) throws SynapseException { ValidateArgument.required(entityId, "entityId"); try { JSONObject obj = EntityFactory.createJSONObjectForEntity(dockerCommit); getSharedClientConnection().postJson(repoEndpoint, ENTITY+"/"+entityId+DOCKER_COMMIT, obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DockerCommit> listDockerCommits( String entityId, Long limit, Long offset, DockerCommitSortBy sortBy, Boolean ascending) throws SynapseException { ValidateArgument.required(entityId, "entityId"); String url = ENTITY+"/"+entityId+DOCKER_COMMIT; List<String> requestParams = new ArrayList<String>(); if (limit!=null) requestParams.add(LIMIT+"="+limit); if (offset!=null) requestParams.add(OFFSET+"="+offset); if (sortBy!=null) requestParams.add("sort="+sortBy.name()); if (ascending!=null) requestParams.add("ascending="+ascending); if (!requestParams.isEmpty()) { url += "?" + Joiner.on('&').join(requestParams); } JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DockerCommit> results = new PaginatedResults<DockerCommit>( DockerCommit.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionThreadBundle> getThreadsForEntity(String entityId, Long limit, Long offset, DiscussionThreadOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(entityId, "entityId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = ENTITY+"/"+entityId+THREADS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter.toString(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionThreadBundle> results = new PaginatedResults<DiscussionThreadBundle>(DiscussionThreadBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityThreadCounts getEntityThreadCount(List<String> entityIds) throws SynapseException { EntityIdList idList = new EntityIdList(); idList.setIdList(entityIds); return asymmetricalPost(repoEndpoint, ENTITY_THREAD_COUNTS, idList , EntityThreadCounts.class, null); } @Override public PaginatedIds getModeratorsForForum(String forumId, Long limit, Long offset) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); String url = FORUM+"/"+forumId+MODERATORS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; try { return getJSONEntity(url, PaginatedIds.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public BatchFileResult getFileHandleAndUrlBatch(BatchFileRequest request) throws SynapseException { return asymmetricalPost(fileEndpoint, FILE_HANDLE_BATCH, request , BatchFileResult.class, null); } @Override public BatchFileHandleCopyResult copyFileHandles(BatchFileHandleCopyRequest request) throws SynapseException { return asymmetricalPost(fileEndpoint, FILE_HANDLES_COPY, request , BatchFileHandleCopyResult.class, null); } @Override public void requestToCancelSubmission(String submissionId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, EVALUATION_URI_PATH+"/"+SUBMISSION+"/"+submissionId+"/cancellation", getUserAgent()); } @Override public void setUserIpAddress(String ipAddress) { getSharedClientConnection().setUserIp(ipAddress); } }
client/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseClientImpl.java
package org.sagebionetworks.client; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import org.sagebionetworks.client.exceptions.SynapseClientException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.client.exceptions.SynapseResultNotReadyException; import org.sagebionetworks.client.exceptions.SynapseTableUnavailableException; import org.sagebionetworks.client.exceptions.SynapseTermsOfUseException; import org.sagebionetworks.downloadtools.FileUtils; import org.sagebionetworks.evaluation.model.BatchUploadResponse; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.Submission; import org.sagebionetworks.evaluation.model.SubmissionBundle; import org.sagebionetworks.evaluation.model.SubmissionContributor; import org.sagebionetworks.evaluation.model.SubmissionStatus; import org.sagebionetworks.evaluation.model.SubmissionStatusBatch; import org.sagebionetworks.evaluation.model.SubmissionStatusEnum; import org.sagebionetworks.evaluation.model.TeamSubmissionEligibility; import org.sagebionetworks.evaluation.model.UserEvaluationPermissions; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.ACTAccessRequirement; import org.sagebionetworks.repo.model.AccessApproval; import org.sagebionetworks.repo.model.AccessControlList; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.Challenge; import org.sagebionetworks.repo.model.ChallengePagedResults; import org.sagebionetworks.repo.model.ChallengeTeam; import org.sagebionetworks.repo.model.ChallengeTeamPagedResults; import org.sagebionetworks.repo.model.DomainType; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityBundleCreate; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityId; import org.sagebionetworks.repo.model.EntityIdList; import org.sagebionetworks.repo.model.EntityInstanceFactory; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.JoinTeamSignedToken; import org.sagebionetworks.repo.model.ListWrapper; import org.sagebionetworks.repo.model.LogEntry; import org.sagebionetworks.repo.model.MembershipInvitation; import org.sagebionetworks.repo.model.MembershipInvtnSubmission; import org.sagebionetworks.repo.model.MembershipRequest; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.PaginatedIds; import org.sagebionetworks.repo.model.ProjectHeader; import org.sagebionetworks.repo.model.ProjectListSortColumn; import org.sagebionetworks.repo.model.ProjectListType; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.ResponseMessage; import org.sagebionetworks.repo.model.RestrictableObjectDescriptor; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.model.ServiceConstants.AttachmentType; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamMember; import org.sagebionetworks.repo.model.TeamMembershipStatus; import org.sagebionetworks.repo.model.TrashedEntity; import org.sagebionetworks.repo.model.UserBundle; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupHeaderResponsePage; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.UserSessionData; import org.sagebionetworks.repo.model.VersionInfo; import org.sagebionetworks.repo.model.annotation.AnnotationsUtils; import org.sagebionetworks.repo.model.asynch.AsyncJobId; import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus; import org.sagebionetworks.repo.model.asynch.AsynchronousRequestBody; import org.sagebionetworks.repo.model.asynch.AsynchronousResponseBody; import org.sagebionetworks.repo.model.auth.ChangePasswordRequest; import org.sagebionetworks.repo.model.auth.LoginRequest; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.auth.SecretKey; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.auth.Username; import org.sagebionetworks.repo.model.dao.WikiPageKey; import org.sagebionetworks.repo.model.discussion.CreateDiscussionReply; import org.sagebionetworks.repo.model.discussion.CreateDiscussionThread; import org.sagebionetworks.repo.model.discussion.DiscussionFilter; import org.sagebionetworks.repo.model.discussion.DiscussionReplyBundle; import org.sagebionetworks.repo.model.discussion.DiscussionReplyOrder; import org.sagebionetworks.repo.model.discussion.DiscussionThreadBundle; import org.sagebionetworks.repo.model.discussion.DiscussionThreadOrder; import org.sagebionetworks.repo.model.discussion.EntityThreadCounts; import org.sagebionetworks.repo.model.discussion.Forum; import org.sagebionetworks.repo.model.discussion.MessageURL; import org.sagebionetworks.repo.model.discussion.ReplyCount; import org.sagebionetworks.repo.model.discussion.ThreadCount; import org.sagebionetworks.repo.model.discussion.UpdateReplyMessage; import org.sagebionetworks.repo.model.discussion.UpdateThreadMessage; import org.sagebionetworks.repo.model.discussion.UpdateThreadTitle; import org.sagebionetworks.repo.model.docker.DockerCommit; import org.sagebionetworks.repo.model.docker.DockerCommitSortBy; import org.sagebionetworks.repo.model.doi.Doi; import org.sagebionetworks.repo.model.entity.query.EntityQuery; import org.sagebionetworks.repo.model.entity.query.EntityQueryResults; import org.sagebionetworks.repo.model.entity.query.SortDirection; import org.sagebionetworks.repo.model.file.AddPartResponse; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyRequest; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyResult; import org.sagebionetworks.repo.model.file.BatchFileRequest; import org.sagebionetworks.repo.model.file.BatchFileResult; import org.sagebionetworks.repo.model.file.BatchPresignedUploadUrlRequest; import org.sagebionetworks.repo.model.file.BatchPresignedUploadUrlResponse; import org.sagebionetworks.repo.model.file.BulkFileDownloadRequest; import org.sagebionetworks.repo.model.file.BulkFileDownloadResponse; import org.sagebionetworks.repo.model.file.ChunkRequest; import org.sagebionetworks.repo.model.file.ChunkedFileToken; import org.sagebionetworks.repo.model.file.CompleteAllChunksRequest; import org.sagebionetworks.repo.model.file.CompleteChunkedFileRequest; import org.sagebionetworks.repo.model.file.CreateChunkedFileTokenRequest; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.FileHandleAssociation; import org.sagebionetworks.repo.model.file.FileHandleResults; import org.sagebionetworks.repo.model.file.MultipartUploadRequest; import org.sagebionetworks.repo.model.file.MultipartUploadStatus; import org.sagebionetworks.repo.model.file.ProxyFileHandle; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.S3UploadDestination; import org.sagebionetworks.repo.model.file.State; import org.sagebionetworks.repo.model.file.TempFileProviderImpl; import org.sagebionetworks.repo.model.file.UploadDaemonStatus; import org.sagebionetworks.repo.model.file.UploadDestination; import org.sagebionetworks.repo.model.file.UploadDestinationLocation; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.message.MessageBundle; import org.sagebionetworks.repo.model.message.MessageRecipientSet; import org.sagebionetworks.repo.model.message.MessageSortBy; import org.sagebionetworks.repo.model.message.MessageStatus; import org.sagebionetworks.repo.model.message.MessageStatusType; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken; import org.sagebionetworks.repo.model.oauth.OAuthProvider; import org.sagebionetworks.repo.model.oauth.OAuthUrlRequest; import org.sagebionetworks.repo.model.oauth.OAuthUrlResponse; import org.sagebionetworks.repo.model.oauth.OAuthValidationRequest; import org.sagebionetworks.repo.model.principal.AccountSetupInfo; import org.sagebionetworks.repo.model.principal.AddEmailInfo; import org.sagebionetworks.repo.model.principal.AliasCheckRequest; import org.sagebionetworks.repo.model.principal.AliasCheckResponse; import org.sagebionetworks.repo.model.principal.PrincipalAlias; import org.sagebionetworks.repo.model.principal.PrincipalAliasRequest; import org.sagebionetworks.repo.model.principal.PrincipalAliasResponse; import org.sagebionetworks.repo.model.project.ProjectSetting; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.StorageLocationSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.query.QueryTableResults; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.Quiz; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.request.ReferenceList; import org.sagebionetworks.repo.model.search.SearchResults; import org.sagebionetworks.repo.model.search.query.SearchQuery; import org.sagebionetworks.repo.model.status.StackStatus; import org.sagebionetworks.repo.model.subscription.Etag; import org.sagebionetworks.repo.model.subscription.Subscription; import org.sagebionetworks.repo.model.subscription.SubscriptionObjectType; import org.sagebionetworks.repo.model.subscription.SubscriptionPagedResults; import org.sagebionetworks.repo.model.subscription.SubscriptionRequest; import org.sagebionetworks.repo.model.subscription.Topic; import org.sagebionetworks.repo.model.table.AppendableRowSet; import org.sagebionetworks.repo.model.table.AppendableRowSetRequest; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.CsvTableDescriptor; import org.sagebionetworks.repo.model.table.DownloadFromTableRequest; import org.sagebionetworks.repo.model.table.DownloadFromTableResult; import org.sagebionetworks.repo.model.table.PaginatedColumnModels; import org.sagebionetworks.repo.model.table.Query; import org.sagebionetworks.repo.model.table.QueryBundleRequest; import org.sagebionetworks.repo.model.table.QueryNextPageToken; import org.sagebionetworks.repo.model.table.QueryResult; import org.sagebionetworks.repo.model.table.QueryResultBundle; import org.sagebionetworks.repo.model.table.RowReference; import org.sagebionetworks.repo.model.table.RowReferenceSet; import org.sagebionetworks.repo.model.table.RowReferenceSetResults; import org.sagebionetworks.repo.model.table.RowSelection; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.TableFileHandleResults; import org.sagebionetworks.repo.model.table.TableUpdateRequest; import org.sagebionetworks.repo.model.table.TableUpdateResponse; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionResponse; import org.sagebionetworks.repo.model.table.UploadToTablePreviewRequest; import org.sagebionetworks.repo.model.table.UploadToTablePreviewResult; import org.sagebionetworks.repo.model.table.UploadToTableRequest; import org.sagebionetworks.repo.model.table.UploadToTableResult; import org.sagebionetworks.repo.model.table.ViewType; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot; import org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.verification.VerificationPagedResults; import org.sagebionetworks.repo.model.verification.VerificationState; import org.sagebionetworks.repo.model.verification.VerificationStateEnum; import org.sagebionetworks.repo.model.verification.VerificationSubmission; import org.sagebionetworks.repo.model.versionInfo.SynapseVersionInfo; import org.sagebionetworks.repo.model.wiki.WikiHeader; import org.sagebionetworks.repo.model.wiki.WikiPage; import org.sagebionetworks.repo.model.wiki.WikiVersionsList; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.schema.adapter.JSONEntity; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl; import org.sagebionetworks.util.ValidateArgument; import org.sagebionetworks.utils.MD5ChecksumHelper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; /** * Low-level Java Client API for Synapse REST APIs */ public class SynapseClientImpl extends BaseClientImpl implements SynapseClient { public static final String SYNPASE_JAVA_CLIENT = "Synpase-Java-Client/"; public static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; private static final Logger log = LogManager .getLogger(SynapseClientImpl.class.getName()); private static final long MAX_UPLOAD_DAEMON_MS = 60 * 1000; private static final String DEFAULT_REPO_ENDPOINT = "https://repo-prod.prod.sagebase.org/repo/v1"; private static final String DEFAULT_AUTH_ENDPOINT = SharedClientConnection.DEFAULT_AUTH_ENDPOINT; private static final String DEFAULT_FILE_ENDPOINT = "https://repo-prod.prod.sagebase.org/file/v1"; private static final String ACCOUNT = "/account"; private static final String EMAIL_VALIDATION = "/emailValidation"; private static final String ACCOUNT_EMAIL_VALIDATION = ACCOUNT + EMAIL_VALIDATION; private static final String EMAIL = "/email"; private static final String PORTAL_ENDPOINT_PARAM = "portalEndpoint"; private static final String SET_AS_NOTIFICATION_EMAIL_PARAM = "setAsNotificationEmail"; private static final String EMAIL_PARAM = "email"; private static final String PARAM_GENERATED_BY = "generatedBy"; private static final String QUERY = "/query"; private static final String QUERY_URI = QUERY + "?query="; private static final String REPO_SUFFIX_VERSION = "/version"; private static final String ANNOTATION_URI_SUFFIX = "annotations"; protected static final String ADMIN = "/admin"; protected static final String STACK_STATUS = ADMIN + "/synapse/status"; private static final String ENTITY = "/entity"; private static final String GENERATED_BY_SUFFIX = "/generatedBy"; private static final String ENTITY_URI_PATH = "/entity"; private static final String ENTITY_ACL_PATH_SUFFIX = "/acl"; private static final String ENTITY_ACL_RECURSIVE_SUFFIX = "?recursive=true"; private static final String ENTITY_BUNDLE_PATH = "/bundle?mask="; private static final String BUNDLE = "/bundle"; private static final String BENEFACTOR = "/benefactor"; // from // org.sagebionetworks.repo.web.UrlHelpers private static final String ACTIVITY_URI_PATH = "/activity"; private static final String GENERATED_PATH = "/generated"; private static final String FAVORITE_URI_PATH = "/favorite"; private static final String PROJECTS_URI_PATH = "/projects"; public static final String PRINCIPAL = "/principal"; public static final String PRINCIPAL_AVAILABLE = PRINCIPAL + "/available"; public static final String NOTIFICATION_EMAIL = "/notificationEmail"; private static final String WIKI_URI_TEMPLATE = "/%1$s/%2$s/wiki"; private static final String WIKI_ID_URI_TEMPLATE = "/%1$s/%2$s/wiki/%3$s"; private static final String WIKI_TREE_URI_TEMPLATE = "/%1$s/%2$s/wikiheadertree"; private static final String WIKI_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2"; private static final String WIKI_ID_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2/%3$s"; private static final String WIKI_ID_VERSION_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2/%3$s/%4$s"; private static final String WIKI_TREE_URI_TEMPLATE_V2 = "/%1$s/%2$s/wikiheadertree2"; private static final String WIKI_ORDER_HINT_URI_TEMPLATE_V2 = "/%1$s/%2$s/wiki2orderhint"; private static final String WIKI_HISTORY_V2 = "/wikihistory"; private static final String ATTACHMENT_HANDLES = "/attachmenthandles"; private static final String ATTACHMENT_FILE = "/attachment"; private static final String MARKDOWN_FILE = "/markdown"; private static final String ATTACHMENT_FILE_PREVIEW = "/attachmentpreview"; private static final String FILE_NAME_PARAMETER = "?fileName="; private static final String REDIRECT_PARAMETER = "redirect="; private static final String OFFSET_PARAMETER = "offset="; private static final String LIMIT_PARAMETER = "limit="; private static final String VERSION_PARAMETER = "?wikiVersion="; private static final String AND_VERSION_PARAMETER = "&wikiVersion="; private static final String AND_LIMIT_PARAMETER = "&" + LIMIT_PARAMETER; private static final String AND_REDIRECT_PARAMETER = "&" + REDIRECT_PARAMETER; private static final String QUERY_REDIRECT_PARAMETER = "?" + REDIRECT_PARAMETER; private static final String ACCESS_TYPE_PARAMETER = "accessType"; private static final String EVALUATION_URI_PATH = "/evaluation"; private static final String AVAILABLE_EVALUATION_URI_PATH = "/evaluation/available"; private static final String NAME = "name"; private static final String ALL = "/all"; private static final String STATUS = "/status"; private static final String STATUS_BATCH = "/statusBatch"; private static final String LOCK_ACCESS_REQUIREMENT = "/lockAccessRequirement"; private static final String SUBMISSION = "submission"; private static final String SUBMISSION_BUNDLE = SUBMISSION + BUNDLE; private static final String SUBMISSION_ALL = SUBMISSION + ALL; private static final String SUBMISSION_STATUS_ALL = SUBMISSION + STATUS + ALL; private static final String SUBMISSION_BUNDLE_ALL = SUBMISSION + BUNDLE + ALL; private static final String STATUS_SUFFIX = "?status="; private static final String EVALUATION_ACL_URI_PATH = "/evaluation/acl"; private static final String EVALUATION_QUERY_URI_PATH = EVALUATION_URI_PATH + "/" + SUBMISSION + QUERY_URI; private static final String EVALUATION_IDS_FILTER_PARAM = "evaluationIds"; private static final String SUBMISSION_ELIGIBILITY = "/submissionEligibility"; private static final String SUBMISSION_ELIGIBILITY_HASH = "submissionEligibilityHash"; private static final String MESSAGE = "/message"; private static final String FORWARD = "/forward"; private static final String CONVERSATION = "/conversation"; private static final String MESSAGE_STATUS = MESSAGE + "/status"; private static final String MESSAGE_INBOX = MESSAGE + "/inbox"; private static final String MESSAGE_OUTBOX = MESSAGE + "/outbox"; private static final String MESSAGE_INBOX_FILTER_PARAM = "inboxFilter"; private static final String MESSAGE_ORDER_BY_PARAM = "orderBy"; private static final String MESSAGE_DESCENDING_PARAM = "descending"; protected static final String ASYNC_START = "/async/start"; protected static final String ASYNC_GET = "/async/get/"; protected static final String COLUMN = "/column"; protected static final String COLUMN_BATCH = COLUMN + "/batch"; protected static final String COLUMN_VIEW_DEFAULT = COLUMN + "/tableview/defaults/"; protected static final String TABLE = "/table"; protected static final String ROW_ID = "/row"; protected static final String ROW_VERSION = "/version"; protected static final String TABLE_QUERY = TABLE + "/query"; protected static final String TABLE_QUERY_NEXTPAGE = TABLE_QUERY + "/nextPage"; protected static final String TABLE_DOWNLOAD_CSV = TABLE + "/download/csv"; protected static final String TABLE_UPLOAD_CSV = TABLE + "/upload/csv"; protected static final String TABLE_UPLOAD_CSV_PREVIEW = TABLE + "/upload/csv/preview"; protected static final String TABLE_APPEND = TABLE + "/append"; protected static final String TABLE_TRANSACTION = TABLE+"/transaction"; protected static final String ASYNCHRONOUS_JOB = "/asynchronous/job"; private static final String USER_PROFILE_PATH = "/userProfile"; private static final String NOTIFICATION_SETTINGS = "/notificationSettings"; private static final String PROFILE_IMAGE = "/image"; private static final String PROFILE_IMAGE_PREVIEW = PROFILE_IMAGE+"/preview"; private static final String USER_GROUP_HEADER_BATCH_PATH = "/userGroupHeaders/batch?ids="; private static final String USER_GROUP_HEADER_PREFIX_PATH = "/userGroupHeaders?prefix="; private static final String TOTAL_NUM_RESULTS = "totalNumberOfResults"; private static final String ACCESS_REQUIREMENT = "/accessRequirement"; private static final String ACCESS_REQUIREMENT_UNFULFILLED = "/accessRequirementUnfulfilled"; private static final String ACCESS_APPROVAL = "/accessApproval"; private static final String VERSION_INFO = "/version"; private static final String FILE_HANDLE = "/fileHandle"; private static final String FILE = "/file"; private static final String FILE_PREVIEW = "/filepreview"; private static final String EXTERNAL_FILE_HANDLE = "/externalFileHandle"; private static final String EXTERNAL_FILE_HANDLE_S3 = "/externalFileHandle/s3"; private static final String EXTERNAL_FILE_HANDLE_PROXY = "/externalFileHandle/proxy"; private static final String FILE_HANDLES = "/filehandles"; protected static final String S3_FILE_COPY = FILE + "/s3FileCopy"; private static final String FILE_HANDLES_COPY = FILE_HANDLES+"/copy"; protected static final String FILE_BULK = FILE+"/bulk"; private static final String CREATE_CHUNKED_FILE_UPLOAD_TOKEN = "/createChunkedFileUploadToken"; private static final String CREATE_CHUNKED_FILE_UPLOAD_CHUNK_URL = "/createChunkedFileUploadChunkURL"; private static final String START_COMPLETE_UPLOAD_DAEMON = "/startCompleteUploadDaemon"; private static final String COMPLETE_UPLOAD_DAEMON_STATUS = "/completeUploadDaemonStatus"; private static final String TRASHCAN_TRASH = "/trashcan/trash"; private static final String TRASHCAN_RESTORE = "/trashcan/restore"; private static final String TRASHCAN_VIEW = "/trashcan/view"; private static final String TRASHCAN_PURGE = "/trashcan/purge"; private static final String CHALLENGE = "/challenge"; private static final String REGISTRATABLE_TEAM = "/registratableTeam"; private static final String CHALLENGE_TEAM = "/challengeTeam"; private static final String SUBMISSION_TEAMS = "/submissionTeams"; private static final String LOG = "/log"; private static final String DOI = "/doi"; private static final String ETAG = "etag"; private static final String PROJECT_SETTINGS = "/projectSettings"; private static final String STORAGE_LOCATION = "/storageLocation"; public static final String AUTH_OAUTH_2 = "/oauth2"; public static final String AUTH_OAUTH_2_AUTH_URL = AUTH_OAUTH_2+"/authurl"; public static final String AUTH_OAUTH_2_SESSION = AUTH_OAUTH_2+"/session"; public static final String AUTH_OAUTH_2_ALIAS = AUTH_OAUTH_2+"/alias"; private static final String VERIFICATION_SUBMISSION = "/verificationSubmission"; private static final String CURRENT_VERIFICATION_STATE = "currentVerificationState"; private static final String VERIFICATION_STATE = "/state"; private static final String VERIFIED_USER_ID = "verifiedUserId"; private static final String USER_BUNDLE = "/bundle"; private static final String FILE_ASSOCIATE_TYPE = "fileAssociateType"; private static final String FILE_ASSOCIATE_ID = "fileAssociateId"; public static final String FILE_HANDLE_BATCH = "/fileHandle/batch"; // web request pagination parameters public static final String LIMIT = "limit"; public static final String OFFSET = "offset"; private static final long MAX_BACKOFF_MILLIS = 5 * 60 * 1000L; // five // minutes /** * The character encoding to use with strings which are the body of email * messages */ private static final Charset MESSAGE_CHARSET = Charset.forName("UTF-8"); private static final String LIMIT_1_OFFSET_1 = "' limit 1 offset 1"; private static final String SELECT_ID_FROM_ENTITY_WHERE_PARENT_ID = "select id from entity where parentId == '"; // Team protected static final String TEAM = "/team"; protected static final String TEAMS = "/teams"; private static final String TEAM_LIST = "/teamList"; private static final String MEMBER_LIST = "/memberList"; protected static final String USER = "/user"; protected static final String NAME_FRAGMENT_FILTER = "fragment"; protected static final String ICON = "/icon"; protected static final String TEAM_MEMBERS = "/teamMembers"; protected static final String MEMBER = "/member"; protected static final String PERMISSION = "/permission"; protected static final String MEMBERSHIP_STATUS = "/membershipStatus"; protected static final String TEAM_MEMBERSHIP_PERMISSION = "isAdmin"; // membership invitation private static final String MEMBERSHIP_INVITATION = "/membershipInvitation"; private static final String OPEN_MEMBERSHIP_INVITATION = "/openInvitation"; private static final String TEAM_ID_REQUEST_PARAMETER = "teamId"; private static final String INVITEE_ID_REQUEST_PARAMETER = "inviteeId"; // membership request private static final String MEMBERSHIP_REQUEST = "/membershipRequest"; private static final String OPEN_MEMBERSHIP_REQUEST = "/openRequest"; private static final String REQUESTOR_ID_REQUEST_PARAMETER = "requestorId"; public static final String ACCEPT_INVITATION_ENDPOINT_PARAM = "acceptInvitationEndpoint"; public static final String ACCEPT_REQUEST_ENDPOINT_PARAM = "acceptRequestEndpoint"; public static final String NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM = "notificationUnsubscribeEndpoint"; public static final String TEAM_ENDPOINT_PARAM = "teamEndpoint"; public static final String CHALLENGE_ENDPOINT_PARAM = "challengeEndpoint"; private static final String CERTIFIED_USER_TEST = "/certifiedUserTest"; private static final String CERTIFIED_USER_TEST_RESPONSE = "/certifiedUserTestResponse"; private static final String CERTIFIED_USER_PASSING_RECORD = "/certifiedUserPassingRecord"; private static final String CERTIFIED_USER_PASSING_RECORDS = "/certifiedUserPassingRecords"; private static final String CERTIFIED_USER_STATUS = "/certificationStatus"; private static final String PROJECT = "/project"; private static final String FORUM = "/forum"; private static final String THREAD = "/thread"; private static final String THREADS = "/threads"; private static final String THREAD_COUNT = "/threadcount"; private static final String THREAD_TITLE = "/title"; private static final String DISCUSSION_MESSAGE = "/message"; private static final String REPLY = "/reply"; private static final String REPLIES = "/replies"; private static final String REPLY_COUNT = "/replycount"; private static final String URL = "/messageUrl"; private static final String PIN = "/pin"; private static final String UNPIN = "/unpin"; private static final String RESTORE = "/restore"; private static final String MODERATORS = "/moderators"; private static final String THREAD_COUNTS = "/threadcounts"; private static final String ENTITY_THREAD_COUNTS = ENTITY + THREAD_COUNTS; private static final String SUBSCRIPTION = "/subscription"; private static final String LIST = "/list"; private static final String OBJECT_TYPE_PARAM = "objectType"; private static final String OBJECT = "/object"; private static final String PRINCIPAL_ID_REQUEST_PARAM = "principalId"; private static final String DOCKER_COMMIT = "/dockerCommit"; protected String repoEndpoint; protected String authEndpoint; protected String fileEndpoint; /** * The maximum number of threads that should be used to upload asynchronous * file chunks. */ private static final int MAX_NUMBER_OF_THREADS = 2; /** * This thread pool is used for asynchronous file chunk uploads. */ private ExecutorService fileUplaodthreadPool = Executors .newFixedThreadPool(MAX_NUMBER_OF_THREADS); /** * Note: 5 MB is currently the minimum size of a single part of S3 * Multi-part upload, so any file chunk must be at least this size. */ public static final int MINIMUM_CHUNK_SIZE_BYTES = ((int) Math.pow(2, 20)) * 5; /** * Default constructor uses the default repository and auth services * endpoints. */ public SynapseClientImpl() { // Use the default implementations this(new SharedClientConnection(new HttpClientProviderImpl())); } /** * Will use the same connection as the other client * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(BaseClient other) { this(other.getSharedClientConnection()); } /** * Will use the shared connection provider and data uploader. * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(SharedClientConnection sharedClientConnection) { super(SYNPASE_JAVA_CLIENT + ClientVersionInfo.getClientVersionInfo(), sharedClientConnection); if (sharedClientConnection == null) throw new IllegalArgumentException( "SharedClientConnection cannot be null"); setRepositoryEndpoint(DEFAULT_REPO_ENDPOINT); setAuthEndpoint(DEFAULT_AUTH_ENDPOINT); setFileEndpoint(DEFAULT_FILE_ENDPOINT); } /** * Default constructor uses the default repository and auth services * endpoints. */ public SynapseClientImpl(DomainType domain) { // Use the default implementations this(new HttpClientProviderImpl(), domain); } /** * Will use the provided client provider and data uploader. * * @param clientProvider * @param dataUploader */ public SynapseClientImpl(HttpClientProvider clientProvider, DomainType domain) { this(new SharedClientConnection(clientProvider, domain)); } /** * Use this method to override the default implementation of * {@link HttpClientProvider} * * @param clientProvider */ public void setHttpClientProvider(HttpClientProvider clientProvider) { getSharedClientConnection().setHttpClientProvider(clientProvider); } /** * Returns a helper class for making specialized Http requests * */ private HttpClientHelper getHttpClientHelper() { return new HttpClientHelper(getSharedClientConnection().getHttpClientProvider()); } /** * @param repoEndpoint * the repoEndpoint to set */ @Override public void setRepositoryEndpoint(String repoEndpoint) { this.repoEndpoint = repoEndpoint; } /** * Get the configured Repository Service Endpoint * * @return */ @Override public String getRepoEndpoint() { return repoEndpoint; } /** * @param authEndpoint * the authEndpoint to set */ @Override public void setAuthEndpoint(String authEndpoint) { this.authEndpoint = authEndpoint; getSharedClientConnection().setAuthEndpoint(authEndpoint); } /** * Get the configured Authorization Service Endpoint * * @return */ @Override public String getAuthEndpoint() { return authEndpoint; } /** * @param fileEndpoint * the authEndpoint to set */ @Override public void setFileEndpoint(String fileEndpoint) { this.fileEndpoint = fileEndpoint; } /** * The endpoint used for file multi-part upload. * * @return */ @Override public String getFileEndpoint() { return this.fileEndpoint; } /** * Lookup the endpoint for a given type. * @param type * @return */ String getEndpointForType(RestEndpointType type){ switch(type){ case auth: return getAuthEndpoint(); case repo: return getRepoEndpoint(); case file: return getFileEndpoint(); default: throw new IllegalArgumentException("Unknown type: "+type); } } /** * @param request */ @Override public void setRequestProfile(boolean request) { getSharedClientConnection().setRequestProfile(request); } /** * @return JSONObject */ @Override public JSONObject getProfileData() { return getSharedClientConnection().getProfileData(); } /** * @return the userName */ @Override public String getUserName() { return getSharedClientConnection().getUserName(); } /** * @param userName * the userName to set */ @Override public void setUserName(String userName) { getSharedClientConnection().setUserName(userName); } /** * @return the apiKey */ @Override public String getApiKey() { return getSharedClientConnection().getApiKey(); } /** * @param apiKey * the apiKey to set */ @Override public void setApiKey(String apiKey) { getSharedClientConnection().setApiKey(apiKey); } @Deprecated @Override public Session login(String username, String password) throws SynapseException { return getSharedClientConnection().login(username, password, getUserAgent()); } @Override public LoginResponse login(LoginRequest request) throws SynapseException { return getSharedClientConnection().login(request, getUserAgent()); } @Override public void logout() throws SynapseException { getSharedClientConnection().logout(getUserAgent()); } @Override public UserSessionData getUserSessionData() throws SynapseException { Session session = new Session(); session.setSessionToken(getCurrentSessionToken()); try { revalidateSession(); session.setAcceptsTermsOfUse(true); } catch (SynapseTermsOfUseException e) { session.setAcceptsTermsOfUse(false); } UserSessionData userData = null; userData = new UserSessionData(); userData.setSession(session); if (session.getAcceptsTermsOfUse()) { userData.setProfile(getMyProfile()); } return userData; } @Override public boolean revalidateSession() throws SynapseException { return getSharedClientConnection().revalidateSession(getUserAgent()); } /******************** * Mid Level Repository Service APIs * * @throws SynapseException ********************/ @Override public AliasCheckResponse checkAliasAvailable(AliasCheckRequest request) throws SynapseException { String url = PRINCIPAL_AVAILABLE; return asymmetricalPost(getRepoEndpoint(), url, request, AliasCheckResponse.class, null); } /** * Send an email validation message as a precursor to creating a new user * account. * * @param user * the first name, last name and email address for the new user * @param portalEndpoint * the GUI endpoint (is the basis for the link in the email * message) Must generate a valid email when a set of request * parameters is appended to the end. */ @Override public void newAccountEmailValidation(NewUser user, String portalEndpoint) throws SynapseException { if (user == null) throw new IllegalArgumentException("email can not be null."); if (portalEndpoint == null) throw new IllegalArgumentException( "portalEndpoint can not be null."); String uri = ACCOUNT_EMAIL_VALIDATION; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(PORTAL_ENDPOINT_PARAM, portalEndpoint); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(user.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Create a new account, following email validation. Sets the password and * logs the user in, returning a valid session token * * @param accountSetupInfo * Note: Caller may override the first/last name, but not the * email, given in 'newAccountEmailValidation' * @return session * @throws NotFoundException */ @Override public Session createNewAccount(AccountSetupInfo accountSetupInfo) throws SynapseException { if (accountSetupInfo == null) throw new IllegalArgumentException( "accountSetupInfo can not be null."); String uri = ACCOUNT; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(accountSetupInfo.writeToJSONObject( toUpdateAdapter).toJSONString()); JSONObject result = getSharedClientConnection().postJson( repoEndpoint, uri, obj.toString(), getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(result, Session.class); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Send an email validation as a precursor to adding a new email address to * an existing account. * * @param email * the email which is claimed by the user * @param portalEndpoint * the GUI endpoint (is the basis for the link in the email * message) Must generate a valid email when a set of request * parameters is appended to the end. * @throws NotFoundException */ @Override public void additionalEmailValidation(Long userId, String email, String portalEndpoint) throws SynapseException { if (userId == null) throw new IllegalArgumentException("userId can not be null."); if (email == null) throw new IllegalArgumentException("email can not be null."); if (portalEndpoint == null) throw new IllegalArgumentException( "portalEndpoint can not be null."); String uri = ACCOUNT + "/" + userId + EMAIL_VALIDATION; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(PORTAL_ENDPOINT_PARAM, portalEndpoint); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { Username emailRequestBody = new Username(); emailRequestBody.setEmail(email); JSONObject obj = new JSONObject(emailRequestBody.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Add a new email address to an existing account. * * @param addEmailInfo * the token sent to the user via email * @param setAsNotificationEmail * if true then set the new email address to be the user's * notification address * @throws NotFoundException */ @Override public void addEmail(AddEmailInfo addEmailInfo, Boolean setAsNotificationEmail) throws SynapseException { if (addEmailInfo == null) throw new IllegalArgumentException("addEmailInfo can not be null."); String uri = EMAIL; Map<String, String> paramMap = new HashMap<String, String>(); if (setAsNotificationEmail != null) paramMap.put(SET_AS_NOTIFICATION_EMAIL_PARAM, setAsNotificationEmail.toString()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); try { JSONObject obj = new JSONObject(addEmailInfo.writeToJSONObject( toUpdateAdapter).toJSONString()); getSharedClientConnection().postJson(repoEndpoint, uri, obj.toString(), getUserAgent(), paramMap); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Remove an email address from an existing account. * * @param email * the email to remove. Must be an established email address for * the user * @throws NotFoundException */ @Override public void removeEmail(String email) throws SynapseException { if (email == null) throw new IllegalArgumentException("email can not be null."); String uri = EMAIL; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(EMAIL_PARAM, email); getSharedClientConnection().deleteUri(repoEndpoint, uri, getUserAgent(), paramMap); } /** * This sets the email used for user notifications, i.e. when a Synapse * message is sent and if the user has elected to receive messages by email, * then this is the email address at which the user will receive the * message. Note: The given email address must already be established as * being owned by the user. */ public void setNotificationEmail(String email) throws SynapseException { if (email == null) { throw new IllegalArgumentException("email can not be null."); } String url = NOTIFICATION_EMAIL; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { Username un = new Username(); un.setEmail(email); obj = new JSONObject(un.writeToJSONObject(toUpdateAdapter) .toJSONString()); getSharedClientConnection().putJson(repoEndpoint, url, obj.toString(), getUserAgent()); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * This gets the email used for user notifications, i.e. when a Synapse * message is sent and if the user has elected to receive messages by email, * then this is the email address at which the user will receive the * message. * * @throws SynapseException */ public String getNotificationEmail() throws SynapseException { String url = NOTIFICATION_EMAIL; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { Username un = new Username(); un.initializeFromJSONObject(adapter); return un.getEmail(); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Create a new dataset, layer, etc ... * * @param uri * @param entity * @return the newly created entity * @throws SynapseException */ @Override public JSONObject createJSONObject(String uri, JSONObject entity) throws SynapseException { return getSharedClientConnection().postJson(repoEndpoint, uri, entity.toString(), getUserAgent(), null); } /** * Create a new Entity. * * @param <T> * @param entity * @return the newly created entity * @throws SynapseException */ @Override public <T extends Entity> T createEntity(T entity) throws SynapseException { return createEntity(entity, null); } /** * Create a new Entity. * * @param <T> * @param entity * @param activityId * set generatedBy relationship to the new entity * @return the newly created entity * @throws SynapseException */ @Override public <T extends Entity> T createEntity(T entity, String activityId) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); entity.setConcreteType(entity.getClass().getName()); String uri = ENTITY_URI_PATH; if (activityId != null) uri += "?" + PARAM_GENERATED_BY + "=" + activityId; return createJSONEntity(uri, entity); } /** * Create a new Entity. * * @param <T> * @param entity * @return the newly created entity * @throws SynapseException */ @Override @SuppressWarnings("unchecked") public <T extends JSONEntity> T createJSONEntity(String uri, T entity) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(entity); // Create the entity jsonObject = createJSONObject(uri, jsonObject); // Now convert to Object to an entity return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public <T extends JSONEntity> List<T> createJSONEntityFromListWrapper(String uri, ListWrapper<T> entity, Class<T> elementType) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); try { String jsonString = EntityFactory.createJSONStringForEntity(entity); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), uri, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), elementType); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Create an Entity, Annotations, and ACL with a single call. * * @param ebc * @return * @throws SynapseException */ @Override public EntityBundle createEntityBundle(EntityBundleCreate ebc) throws SynapseException { return createEntityBundle(ebc, null); } /** * Create an Entity, Annotations, and ACL with a single call. * * @param ebc * @param activityId * the activity to create a generatedBy relationship with the * entity in the Bundle. * @return * @throws SynapseException */ @Override public EntityBundle createEntityBundle(EntityBundleCreate ebc, String activityId) throws SynapseException { if (ebc == null) throw new IllegalArgumentException("EntityBundle cannot be null"); String url = ENTITY_URI_PATH + BUNDLE; JSONObject jsonObject; if (activityId != null) url += "?" + PARAM_GENERATED_BY + "=" + activityId; try { // Convert to JSON jsonObject = EntityFactory.createJSONObjectForEntity(ebc); // Create jsonObject = createJSONObject(url, jsonObject); // Convert returned JSON to EntityBundle return EntityFactory.createEntityFromJSONObject(jsonObject, EntityBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Update an Entity, Annotations, and ACL with a single call. * * @param ebc * @return * @throws SynapseException */ @Override public EntityBundle updateEntityBundle(String entityId, EntityBundleCreate ebc) throws SynapseException { return updateEntityBundle(entityId, ebc, null); } /** * Update an Entity, Annotations, and ACL with a single call. * * @param ebc * @param activityId * the activity to create a generatedBy relationship with the * entity in the Bundle. * @return * @throws SynapseException */ @Override public EntityBundle updateEntityBundle(String entityId, EntityBundleCreate ebc, String activityId) throws SynapseException { if (ebc == null) throw new IllegalArgumentException("EntityBundle cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + BUNDLE; JSONObject jsonObject; try { // Convert to JSON jsonObject = EntityFactory.createJSONObjectForEntity(ebc); // Update. Bundles do not have their own etags, so we use an // empty requestHeaders object. jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); // Convert returned JSON to EntityBundle return EntityFactory.createEntityFromJSONObject(jsonObject, EntityBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get an entity using its ID. * * @param entityId * @return the entity * @throws SynapseException */ @Override public Entity getEntityById(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); return getEntityByIdForVersion(entityId, null); } /** * Get a specific version of an entity using its ID an version number. * * @param entityId * @param versionNumber * @return the entity * @throws SynapseException */ @Override public Entity getEntityByIdForVersion(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId; if (versionNumber != null) { url += REPO_SUFFIX_VERSION + "/" + versionNumber; } JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); // Get the type from the object if (!adapter.has("entityType")) throw new RuntimeException("EntityType returned was null!"); try { String entityType = adapter.getString("entityType"); Entity entity = (Entity) EntityInstanceFactory.singleton().newInstance(entityType); entity.initializeFromJSONObject(adapter); return entity; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get a bundle of information about an entity in a single call. * * @param entityId * @param partsMask * @return * @throws SynapseException */ @Override public EntityBundle getEntityBundle(String entityId, int partsMask) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + ENTITY_BUNDLE_PATH + partsMask; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { EntityBundle eb = new EntityBundle(); eb.initializeFromJSONObject(adapter); return eb; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get a bundle of information about an entity in a single call. * * @param entityId * - the entity id to retrieve * @param versionNumber * - the specific version to retrieve * @param partsMask * @return * @throws SynapseException */ @Override public EntityBundle getEntityBundle(String entityId, Long versionNumber, int partsMask) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (versionNumber == null) throw new IllegalArgumentException("versionNumber cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + REPO_SUFFIX_VERSION + "/" + versionNumber + ENTITY_BUNDLE_PATH + partsMask; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { EntityBundle eb = new EntityBundle(); eb.initializeFromJSONObject(adapter); return eb; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * * @param entityId * @return * @throws SynapseException */ @Override public PaginatedResults<VersionInfo> getEntityVersions(String entityId, int offset, int limit) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = ENTITY_URI_PATH + "/" + entityId + REPO_SUFFIX_VERSION + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<VersionInfo> results = new PaginatedResults<VersionInfo>( VersionInfo.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public static <T extends JSONEntity> T initializeFromJSONObject( JSONObject o, Class<T> clazz) throws SynapseException { try { T obj = clazz.newInstance(); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(o); Iterator<String> it = adapter.keys(); while (it.hasNext()) { String s = it.next(); log.trace(s); } obj.initializeFromJSONObject(adapter); return obj; } catch (IllegalAccessException e) { throw new SynapseClientException(e); } catch (InstantiationException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getACL(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, AccessControlList.class); } @Override public EntityHeader getEntityBenefactor(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + BENEFACTOR; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, EntityHeader.class); } @Override public UserProfile getMyProfile() throws SynapseException { String uri = USER_PROFILE_PATH; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserProfile.class); } @Override public void updateMyProfile(UserProfile userProfile) throws SynapseException { try { String uri = USER_PROFILE_PATH; getSharedClientConnection().putJson( repoEndpoint, uri, EntityFactory.createJSONObjectForEntity(userProfile) .toString(), getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ResponseMessage updateNotificationSettings(NotificationSettingsSignedToken token) throws SynapseException { return asymmetricalPut(getRepoEndpoint(), NOTIFICATION_SETTINGS, token, ResponseMessage.class); } @Override public UserProfile getUserProfile(String ownerId) throws SynapseException { String uri = USER_PROFILE_PATH + "/" + ownerId; JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserProfile.class); } /** * Batch get headers for users/groups matching a list of Synapse IDs. * * @param ids * @return * @throws JSONException * @throws SynapseException */ @Override public UserGroupHeaderResponsePage getUserGroupHeadersByIds(List<String> ids) throws SynapseException { String uri = listToString(ids); JSONObject json = getEntity(uri); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getUserProfilePictureUrl(java.lang.String) */ @Override public URL getUserProfilePictureUrl(String ownerId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = USER_PROFILE_PATH+"/"+ownerId+PROFILE_IMAGE+"?"+REDIRECT_PARAMETER+"false"; return getUrl(url); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getUserProfilePicturePreviewUrl(java.lang.String) */ @Override public URL getUserProfilePicturePreviewUrl(String ownerId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = USER_PROFILE_PATH+"/"+ownerId+PROFILE_IMAGE_PREVIEW+"?"+REDIRECT_PARAMETER+"false"; return getUrl(url); } private String listToString(List<String> ids) { StringBuilder sb = new StringBuilder(); sb.append(USER_GROUP_HEADER_BATCH_PATH); for (String id : ids) { sb.append(id); sb.append(','); } // Remove the trailing comma sb.deleteCharAt(sb.length() - 1); return sb.toString(); } @Override public UserGroupHeaderResponsePage getUserGroupHeadersByPrefix(String prefix) throws SynapseException, UnsupportedEncodingException { String encodedPrefix = URLEncoder.encode(prefix, "UTF-8"); JSONObject json = getEntity(USER_GROUP_HEADER_PREFIX_PATH + encodedPrefix); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } @Override public UserGroupHeaderResponsePage getUserGroupHeadersByPrefix( String prefix, long limit, long offset) throws SynapseException, UnsupportedEncodingException { String encodedPrefix = URLEncoder.encode(prefix, "UTF-8"); JSONObject json = getEntity(USER_GROUP_HEADER_PREFIX_PATH + encodedPrefix + "&" + LIMIT_PARAMETER + limit + "&" + OFFSET_PARAMETER + offset); return initializeFromJSONObject(json, UserGroupHeaderResponsePage.class); } /** * Update an ACL. Default to non-recursive application. */ @Override public AccessControlList updateACL(AccessControlList acl) throws SynapseException { return updateACL(acl, false); } /** * Update an entity's ACL. If 'recursive' is set to true, then any child * ACLs will be deleted, such that all child entities inherit this ACL. */ @Override public AccessControlList updateACL(AccessControlList acl, boolean recursive) throws SynapseException { String entityId = acl.getId(); String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; if (recursive) uri += ENTITY_ACL_RECURSIVE_SUFFIX; try { JSONObject jsonAcl = EntityFactory.createJSONObjectForEntity(acl); jsonAcl = getSharedClientConnection().putJson(repoEndpoint, uri, jsonAcl.toString(), getUserAgent()); return initializeFromJSONObject(jsonAcl, AccessControlList.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteACL(String entityId) throws SynapseException { String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public AccessControlList createACL(AccessControlList acl) throws SynapseException { String entityId = acl.getId(); String uri = ENTITY_URI_PATH + "/" + entityId + ENTITY_ACL_PATH_SUFFIX; try { JSONObject jsonAcl = EntityFactory.createJSONObjectForEntity(acl); jsonAcl = createJSONObject(uri, jsonAcl); return initializeFromJSONObject(jsonAcl, AccessControlList.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<UserProfile> getUsers(int offset, int limit) throws SynapseException { String uri = "/user?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonUsers = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonUsers); PaginatedResults<UserProfile> results = new PaginatedResults<UserProfile>( UserProfile.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<UserProfile> listUserProfiles(List<Long> userIds) throws SynapseException { try { IdList idList = new IdList(); idList.setList(userIds); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), USER_PROFILE_PATH, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), UserProfile.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<UserGroup> getGroups(int offset, int limit) throws SynapseException { String uri = "/userGroup?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonUsers = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonUsers); PaginatedResults<UserGroup> results = new PaginatedResults<UserGroup>( UserGroup.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the current user's permission for a given entity. * * @param entityId * @return * @throws SynapseException */ @Override public UserEntityPermissions getUsersEntityPermissions(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/permissions"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserEntityPermissions uep = new UserEntityPermissions(); try { uep.initializeFromJSONObject(adapter); return uep; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the current user's permission for a given entity. * * @param entityId * @return * @throws SynapseException */ @Override public boolean canAccess(String entityId, ACCESS_TYPE accessType) throws SynapseException { return canAccess(entityId, ObjectType.ENTITY, accessType); } @Override public boolean canAccess(String id, ObjectType type, ACCESS_TYPE accessType) throws SynapseException { if (id == null) throw new IllegalArgumentException("id cannot be null"); if (type == null) throw new IllegalArgumentException("ObjectType cannot be null"); if (accessType == null) throw new IllegalArgumentException("AccessType cannot be null"); if (ObjectType.ENTITY.equals(type)) { return canAccess(ENTITY_URI_PATH + "/" + id + "/access?accessType=" + accessType.name()); } else if (ObjectType.EVALUATION.equals(type)) { return canAccess(EVALUATION_URI_PATH + "/" + id + "/access?accessType=" + accessType.name()); } else throw new IllegalArgumentException("ObjectType not supported: " + type.toString()); } private boolean canAccess(String serviceUrl) throws SynapseException { try { JSONObject jsonObj = getEntity(serviceUrl); String resultString = null; try { resultString = jsonObj.getString("result"); } catch (NullPointerException e) { throw new SynapseClientException(jsonObj.toString(), e); } return Boolean.parseBoolean(resultString); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Get the annotations for an entity. * * @param entityId * @return * @throws SynapseException */ @Override public Annotations getAnnotations(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/annotations"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Annotations annos = new Annotations(); try { annos.initializeFromJSONObject(adapter); return annos; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } /** * Update the annotations of an entity. * * @param entityId * @return * @throws SynapseException */ @Override public Annotations updateAnnotations(String entityId, Annotations updated) throws SynapseException { try { String url = ENTITY_URI_PATH + "/" + entityId + "/annotations"; JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(updated); // Update jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); // Parse the results JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); Annotations annos = new Annotations(); annos.initializeFromJSONObject(adapter); return annos; } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @SuppressWarnings("unchecked") private static Class<AccessRequirement> getAccessRequirementClassFromType( String s) { try { return (Class<AccessRequirement>) Class.forName(s); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessRequirement> T createAccessRequirement(T ar) throws SynapseException { if (ar == null) throw new IllegalArgumentException( "AccessRequirement cannot be null"); ar.setConcreteType(ar.getClass().getName()); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(ar); // Create the entity jsonObject = createJSONObject(ACCESS_REQUIREMENT, jsonObject); // Now convert to Object to an entity return (T) initializeFromJSONObject(jsonObject, getAccessRequirementClassFromType(ar.getConcreteType())); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessRequirement> T updateAccessRequirement(T ar) throws SynapseException { if (ar == null) throw new IllegalArgumentException( "AccessRequirement cannot be null"); String url = createEntityUri(ACCESS_REQUIREMENT + "/", ar.getId() .toString()); try { JSONObject toUpdateJsonObject = EntityFactory .createJSONObjectForEntity(ar); JSONObject updatedJsonObject = getSharedClientConnection().putJson( repoEndpoint, url, toUpdateJsonObject.toString(), getUserAgent()); return (T) initializeFromJSONObject(updatedJsonObject, getAccessRequirementClassFromType(ar.getConcreteType())); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public ACTAccessRequirement createLockAccessRequirement(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); JSONObject jsonObj = getSharedClientConnection().postUri(repoEndpoint, ENTITY + "/" + entityId + LOCK_ACCESS_REQUIREMENT, getUserAgent()); return initializeFromJSONObject(jsonObj, ACTAccessRequirement.class); } @Override public void deleteAccessRequirement(Long arId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ACCESS_REQUIREMENT + "/" + arId, getUserAgent()); } @Override public PaginatedResults<AccessRequirement> getUnmetAccessRequirements( RestrictableObjectDescriptor subjectId, ACCESS_TYPE accessType) throws SynapseException { String uri = null; if (RestrictableObjectType.ENTITY == subjectId.getType()) { uri = ENTITY + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else if (RestrictableObjectType.EVALUATION == subjectId.getType()) { uri = EVALUATION_URI_PATH + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else if (RestrictableObjectType.TEAM == subjectId.getType()) { uri = TEAM + "/" + subjectId.getId() + ACCESS_REQUIREMENT_UNFULFILLED; } else { throw new SynapseClientException("Unsupported type " + subjectId.getType()); } if (accessType != null) { uri += "?" + ACCESS_TYPE_PARAMETER + "=" + accessType; } JSONObject jsonAccessRequirements = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl( jsonAccessRequirements); PaginatedResults<AccessRequirement> results = new PaginatedResults<AccessRequirement>(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessRequirement getAccessRequirement(Long requirementId) throws SynapseException { String uri = ACCESS_REQUIREMENT + "/" + requirementId; JSONObject jsonObj = getEntity(uri); try { return EntityFactory.createEntityFromJSONObject(jsonObj, AccessRequirement.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<AccessRequirement> getAccessRequirements( RestrictableObjectDescriptor subjectId) throws SynapseException { String uri = null; if (RestrictableObjectType.ENTITY == subjectId.getType()) { uri = ENTITY + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else if (RestrictableObjectType.EVALUATION == subjectId.getType()) { uri = EVALUATION_URI_PATH + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else if (RestrictableObjectType.TEAM == subjectId.getType()) { uri = TEAM + "/" + subjectId.getId() + ACCESS_REQUIREMENT; } else { throw new SynapseClientException("Unsupported type " + subjectId.getType()); } JSONObject jsonAccessRequirements = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl( jsonAccessRequirements); PaginatedResults<AccessRequirement> results = new PaginatedResults<AccessRequirement>(AccessRequirement.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") private static Class<AccessApproval> getAccessApprovalClassFromType(String s) { try { return (Class<AccessApproval>) Class.forName(s); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends AccessApproval> T createAccessApproval(T aa) throws SynapseException { if (aa == null) throw new IllegalArgumentException("AccessApproval cannot be null"); aa.setConcreteType(aa.getClass().getName()); // Get the json for this entity JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(aa); // Create the entity jsonObject = createJSONObject(ACCESS_APPROVAL, jsonObject); // Now convert to Object to an entity return (T) initializeFromJSONObject(jsonObject, getAccessApprovalClassFromType(aa.getConcreteType())); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessApproval getAccessApproval(Long approvalId) throws SynapseException { String uri = ACCESS_APPROVAL + "/" + approvalId; JSONObject jsonObj = getEntity(uri); try { return EntityFactory.createEntityFromJSONObject(jsonObj, AccessApproval.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public PaginatedResults<AccessApproval> getEntityAccessApproval(String entityId) throws SynapseException { String uri = ENTITY + "/" + entityId + "/" + ACCESS_APPROVAL; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<AccessApproval> results = new PaginatedResults<AccessApproval>(AccessApproval.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteAccessApproval(Long approvalId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, ACCESS_APPROVAL + "/" + approvalId, getUserAgent()); } @Override public void deleteAccessApprovals(String requirementId, String accessorId) throws SynapseException { String url = ACCESS_APPROVAL + "?requirementId=" + requirementId + "&accessorId=" + accessorId; getSharedClientConnection().deleteUri(repoEndpoint, url, getUserAgent()); } /** * Get a dataset, layer, preview, annotations, etc... * * @return the retrieved entity */ @Override public JSONObject getEntity(String uri) throws SynapseException { return getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); } /** * Get an entity given an Entity ID and the class of the Entity. * * @param <T> * @param entityId * @param clazz * @return the entity * @throws SynapseException */ @Override @SuppressWarnings("cast") public <T extends JSONEntity> T getEntity(String entityId, Class<? extends T> clazz) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (clazz == null) throw new IllegalArgumentException("Entity class cannot be null"); // Build the URI String uri = createEntityUri(ENTITY_URI_PATH, entityId); JSONObject jsonObj = getEntity(uri); // Now convert to Object to an entity try { return (T) EntityFactory.createEntityFromJSONObject(jsonObj, clazz); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Helper to create an Entity URI. * * @param prefix * @param id * @return */ private static String createEntityUri(String prefix, String id) { StringBuilder uri = new StringBuilder(); uri.append(prefix); uri.append("/"); uri.append(id); return uri.toString(); } /** * Update a dataset, layer, preview, annotations, etc... * * @param <T> * @param entity * @return the updated entity * @throws SynapseException */ @Override public <T extends Entity> T putEntity(T entity) throws SynapseException { return putEntity(entity, null); } /** * Update a dataset, layer, preview, annotations, etc... * * @param <T> * @param entity * @param activityId * activity to create generatedBy conenction to * @return the updated entity * @throws SynapseException */ @Override @SuppressWarnings("unchecked") public <T extends Entity> T putEntity(T entity, String activityId) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); try { String uri = createEntityUri(ENTITY_URI_PATH, entity.getId()); if (activityId != null) uri += "?" + PARAM_GENERATED_BY + "=" + activityId; JSONObject jsonObject; jsonObject = EntityFactory.createJSONObjectForEntity(entity); jsonObject = getSharedClientConnection().putJson(repoEndpoint, uri, jsonObject.toString(), getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Deletes a dataset, layer, etc.. This only moves the entity to the trash * can. To permanently delete the entity, use deleteAndPurgeEntity(). */ @Override public <T extends Entity> void deleteEntity(T entity) throws SynapseException { deleteEntity(entity, null); } /** * Deletes a dataset, layer, etc.. By default, it moves the entity to the * trash can. There is the option to skip the trash and delete the entity * permanently. */ @Override public <T extends Entity> void deleteEntity(T entity, Boolean skipTrashCan) throws SynapseException { if (entity == null) { throw new IllegalArgumentException("Entity cannot be null"); } deleteEntityById(entity.getId(), skipTrashCan); } /** * Deletes a dataset, layer, etc.. */ @Override public <T extends Entity> void deleteAndPurgeEntity(T entity) throws SynapseException { deleteEntity(entity); purgeTrashForUser(entity.getId()); } /** * Deletes a dataset, layer, etc.. This only moves the entity to the trash * can. To permanently delete the entity, use deleteAndPurgeEntity(). */ @Override public void deleteEntityById(String entityId) throws SynapseException { deleteEntityById(entityId, null); } /** * Deletes a dataset, layer, etc.. By default, it moves the entity to the * trash can. There is the option to skip the trash and delete the entity * permanently. */ @Override public void deleteEntityById(String entityId, Boolean skipTrashCan) throws SynapseException { if (entityId == null) { throw new IllegalArgumentException("entityId cannot be null"); } String uri = createEntityUri(ENTITY_URI_PATH, entityId); if (skipTrashCan != null && skipTrashCan) { uri = uri + "?" + ServiceConstants.SKIP_TRASH_CAN_PARAM + "=true"; } getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Deletes a dataset, layer, etc.. */ @Override public void deleteAndPurgeEntityById(String entityId) throws SynapseException { deleteEntityById(entityId); purgeTrashForUser(entityId); } @Override public <T extends Entity> void deleteEntityVersion(T entity, Long versionNumber) throws SynapseException { if (entity == null) throw new IllegalArgumentException("Entity cannot be null"); deleteEntityVersionById(entity.getId(), versionNumber); } @Override public void deleteEntityVersionById(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); if (versionNumber == null) throw new IllegalArgumentException("VersionNumber cannot be null"); String uri = createEntityUri(ENTITY_URI_PATH, entityId); uri += REPO_SUFFIX_VERSION + "/" + versionNumber; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Get the hierarchical path to this entity * * @param entity * @return * @throws SynapseException */ @Override public EntityPath getEntityPath(Entity entity) throws SynapseException { return getEntityPath(entity.getId()); } /** * Get the hierarchical path to this entity via its id and urlPrefix * * @param entityId * @param urlPrefix * @return * @throws SynapseException */ @Override public EntityPath getEntityPath(String entityId) throws SynapseException { String url = ENTITY_URI_PATH + "/" + entityId + "/path"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); EntityPath path = new EntityPath(); try { path.initializeFromJSONObject(adapter); return path; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<EntityHeader> getEntityTypeBatch(List<String> entityIds) throws SynapseException { String url = ENTITY_URI_PATH + "/type"; // TODO move UrlHelpers // someplace shared so that we // can UrlHelpers.ENTITY_TYPE url += "?" + ServiceConstants.BATCH_PARAM + "=" + StringUtils.join(entityIds, ServiceConstants.BATCH_PARAM_VALUE_SEPARATOR); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<EntityHeader> getEntityHeaderBatch( List<Reference> references) throws SynapseException { ReferenceList list = new ReferenceList(); list.setReferences(references); String url = ENTITY_URI_PATH + "/header"; JSONObject jsonObject; try { jsonObject = EntityFactory.createJSONObjectForEntity(list); // POST jsonObject = createJSONObject(url, jsonObject); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Perform a query * * @param query * the query to perform * @return the query result * @throws SynapseException */ @Override public JSONObject query(String query) throws SynapseException { return querySynapse(query); } @Override @Deprecated public FileHandleResults createFileHandles(List<File> files) throws SynapseException { if (files == null) throw new IllegalArgumentException("File list cannot be null"); try { List<FileHandle> list = new LinkedList<FileHandle>(); for (File file : files) { // We need to determine the content type of the file String contentType = guessContentTypeFromStream(file); S3FileHandle handle = createFileHandle(file, contentType); list.add(handle); } FileHandleResults results = new FileHandleResults(); results.setList(list); return results; } catch (IOException e) { throw new SynapseClientException(e); } } @Override public FileHandleResults createFileHandles(List<File> files, String parentEntityId) throws SynapseException { if (files == null) throw new IllegalArgumentException("File list cannot be null"); try { List<FileHandle> list = new LinkedList<FileHandle>(); for (File file : files) { // We need to determine the content type of the file String contentType = guessContentTypeFromStream(file); FileHandle handle = createFileHandle(file, contentType, parentEntityId); list.add(handle); } FileHandleResults results = new FileHandleResults(); results.setList(list); return results; } catch (IOException e) { throw new SynapseClientException(e); } } @Override public URL getFileHandleTemporaryUrl(String fileHandleId) throws IOException, SynapseException { String uri = getFileHandleTemporaryURI(fileHandleId, false); return getUrl(getFileEndpoint(), uri); } private String getFileHandleTemporaryURI(String fileHandleId, boolean redirect) { return FILE_HANDLE + "/" + fileHandleId + "/url" + QUERY_REDIRECT_PARAMETER + redirect; } @Override public void downloadFromFileHandleTemporaryUrl(String fileHandleId, File destinationFile) throws SynapseException { String uri = getFileEndpoint() + getFileHandleTemporaryURI(fileHandleId, true); getSharedClientConnection().downloadFromSynapse(uri, null, destinationFile, getUserAgent()); } @Override @Deprecated public S3FileHandle createFileHandle(File temp, String contentType) throws SynapseException, IOException { return createFileHandleUsingChunkedUpload(temp, contentType, null, null); } @Override @Deprecated public S3FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated) throws SynapseException, IOException { return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, null); } @Override public FileHandle createFileHandle(File temp, String contentType, String parentEntityId) throws SynapseException, IOException { return createFileHandle(temp, contentType, null, parentEntityId); } @Override public FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, String parentEntityId) throws SynapseException, IOException { UploadDestination uploadDestination = getDefaultUploadDestination(parentEntityId); return createFileHandle(temp, contentType, shouldPreviewBeCreated, uploadDestination.getStorageLocationId(), uploadDestination.getUploadType()); } @Override public FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, String parentEntityId, Long storageLocationId) throws SynapseException, IOException { UploadDestination uploadDestination = getUploadDestination(parentEntityId, storageLocationId); return createFileHandle(temp, contentType, shouldPreviewBeCreated, storageLocationId, uploadDestination.getUploadType()); } private FileHandle createFileHandle(File temp, String contentType, Boolean shouldPreviewBeCreated, Long storageLocationId, UploadType uploadType) throws SynapseException, IOException { if (storageLocationId == null) { // default to S3 return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, null); } switch (uploadType) { case HTTPS: case SFTP: throw new NotImplementedException("SFTP and HTTPS uploads not implemented yet"); case S3: return createFileHandleUsingChunkedUpload(temp, contentType, shouldPreviewBeCreated, storageLocationId); default: throw new NotImplementedException(uploadType.name() + " uploads not implemented yet"); } } private S3FileHandle createFileHandleUsingChunkedUpload(File temp, String contentType, Boolean shouldPreviewBeCreated, Long storageLocationId) throws SynapseException, IOException { if (temp == null) { throw new IllegalArgumentException("File cannot be null"); } if (contentType == null) { throw new IllegalArgumentException("Content type cannot be null"); } CreateChunkedFileTokenRequest ccftr = new CreateChunkedFileTokenRequest(); ccftr.setStorageLocationId(storageLocationId); ccftr.setContentType(contentType); ccftr.setFileName(temp.getName()); // Calculate the MD5 String md5 = MD5ChecksumHelper.getMD5Checksum(temp); ccftr.setContentMD5(md5); // Start the upload ChunkedFileToken token = createChunkedFileUploadToken(ccftr); // Now break the file into part as needed List<File> fileChunks = FileUtils.chunkFile(temp, MINIMUM_CHUNK_SIZE_BYTES); try { // Upload all of the parts. List<Long> partNumbers = uploadChunks(fileChunks, token); // We can now complete the upload CompleteAllChunksRequest cacr = new CompleteAllChunksRequest(); cacr.setChunkedFileToken(token); cacr.setChunkNumbers(partNumbers); cacr.setShouldPreviewBeGenerated(shouldPreviewBeCreated); // Start the daemon UploadDaemonStatus status = startUploadDeamon(cacr); // Wait for it to complete long start = System.currentTimeMillis(); while (State.COMPLETED != status.getState()) { // Check for failure if (State.FAILED == status.getState()) { throw new SynapseClientException("Upload failed: " + status.getErrorMessage()); } log.debug("Waiting for upload daemon: " + status.toString()); Thread.sleep(1000); status = getCompleteUploadDaemonStatus(status.getDaemonId()); if (System.currentTimeMillis() - start > MAX_UPLOAD_DAEMON_MS) { throw new SynapseClientException( "Timed out waiting for upload daemon: " + status.toString()); } } // Complete the upload return (S3FileHandle) getRawFileHandle(status.getFileHandleId()); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { // Delete any tmep files created by this method. The original file // will not be deleted. FileUtils.deleteAllFilesExcludingException(temp, fileChunks); } } /** * Upload all of the passed file chunks. * * @param fileChunks * @param token * @return * @throws ExecutionException * @throws InterruptedException */ private List<Long> uploadChunks(List<File> fileChunks, ChunkedFileToken token) throws SynapseException { try { List<Long> results = new LinkedList<Long>(); // The future list List<Future<Long>> futureList = new ArrayList<Future<Long>>(); // For each chunk create a worker and add it to the thread pool long chunkNumber = 1; for (File file : fileChunks) { // create a worker for each chunk ChunkRequest request = new ChunkRequest(); request.setChunkedFileToken(token); request.setChunkNumber(chunkNumber); FileChunkUploadWorker worker = new FileChunkUploadWorker(this, request, file); // Add this the the thread pool Future<Long> future = fileUplaodthreadPool.submit(worker); futureList.add(future); chunkNumber++; } // Get all of the results for (Future<Long> future : futureList) { Long partNumber = future.get(); results.add(partNumber); } return results; } catch (Exception e) { throw new SynapseClientException(e); } } /** * <P> * This is a low-level API call for uploading large files. We recomend using * the high-level API call for uploading files * {@link #createFileHandle(File, String)}. * </P> * This is the first step in the low-level API used to upload large files to * Synapse. The resulting {@link ChunkedFileToken} is required for all * subsequent steps. Large file upload is exectued as follows: * <ol> * <li>{@link #createChunkedFileUploadToken(CreateChunkedFileTokenRequest)}</li> * <li>{@link #createChunkedPresignedUrl(ChunkRequest)}</li> * <li>{@link #addChunkToFile(ChunkRequest)}</li> * <li>{@link #completeChunkFileUpload(CompleteChunkedFileRequest)}</li> * </ol> * Steps 2 & 3 are repated in for each file chunk. Note: All chunks can be * sent asynchronously. * * @param ccftr * @return The @link {@link ChunkedFileToken} is required for all subsequent * steps. * @throws JSONObjectAdapterException * @throws SynapseException * @throws IOException * @throws ClientProtocolException */ @Override public ChunkedFileToken createChunkedFileUploadToken( CreateChunkedFileTokenRequest ccftr) throws SynapseException { if (ccftr == null) throw new IllegalArgumentException( "CreateChunkedFileTokenRequest cannot be null"); if (ccftr.getFileName() == null) throw new IllegalArgumentException("FileName cannot be null"); if (ccftr.getContentType() == null) throw new IllegalArgumentException("ContentType cannot be null"); String url = CREATE_CHUNKED_FILE_UPLOAD_TOKEN; return asymmetricalPost(getFileEndpoint(), url, ccftr, ChunkedFileToken.class, null); } /** * <P> * This is a low-level API call for uploading large files. We recomend using * the high-level API call for uploading files * {@link #createFileHandle(File, String)}. * </P> * The second step in the low-level API used to upload large files to * Synapse. This method is used to get a pre-signed URL that can be used to * PUT the data of a single chunk to S3. * * @param chunkRequest * @return * @throws JSONObjectAdapterException * @throws IOException * @throws ClientProtocolException */ @Override public URL createChunkedPresignedUrl(ChunkRequest chunkRequest) throws SynapseException { try { if (chunkRequest == null) { throw new IllegalArgumentException( "ChunkRequest cannot be null"); } String uri = CREATE_CHUNKED_FILE_UPLOAD_CHUNK_URL; String data = EntityFactory.createJSONStringForEntity(chunkRequest); String responseBody = getSharedClientConnection().postStringDirect( getFileEndpoint(), uri, data, getUserAgent()); return new URL(responseBody); } catch (IOException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Put the contents of the passed file to the passed URL. * * @param url * @param file * @throws IOException * @throws ClientProtocolException */ @Override public String putFileToURL(URL url, File file, String contentType) throws SynapseException { return getHttpClientHelper().putFileToURL(url, file, contentType); } /** * Start a daemon that will asycnrhounsously complete the multi-part upload. * * @param cacr * @return * @throws SynapseException */ @Override public UploadDaemonStatus startUploadDeamon(CompleteAllChunksRequest cacr) throws SynapseException { String url = START_COMPLETE_UPLOAD_DAEMON; return asymmetricalPost(getFileEndpoint(), url, cacr, UploadDaemonStatus.class, null); } /** * Get the status of daemon used to complete the multi-part upload. * * @param daemonId * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public UploadDaemonStatus getCompleteUploadDaemonStatus(String daemonId) throws SynapseException { String url = COMPLETE_UPLOAD_DAEMON_STATUS + "/" + daemonId; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { return EntityFactory.createEntityFromJSONObject(json, UploadDaemonStatus.class); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } /** * Create an External File Handle. This is used to references a file that is * not stored in Synpase. * * @param efh * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public ExternalFileHandle createExternalFileHandle(ExternalFileHandle efh) throws JSONObjectAdapterException, SynapseException { String uri = EXTERNAL_FILE_HANDLE; return doCreateJSONEntity(getFileEndpoint(), uri, efh); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#createExternalS3FileHandle(org.sagebionetworks.repo.model.file.S3FileHandle) */ @Override public S3FileHandle createExternalS3FileHandle(S3FileHandle handle) throws JSONObjectAdapterException, SynapseException{ String uri = EXTERNAL_FILE_HANDLE_S3; return doCreateJSONEntity(getFileEndpoint(), uri, handle); } @Override public ProxyFileHandle createExternalProxyFileHandle(ProxyFileHandle handle) throws JSONObjectAdapterException, SynapseException{ return doCreateJSONEntity(getFileEndpoint(), EXTERNAL_FILE_HANDLE_PROXY, handle); } @Override public S3FileHandle createS3FileHandleCopy(String originalFileHandleId, String name, String contentType) throws JSONObjectAdapterException, SynapseException { String uri = FILE_HANDLE + "/" + originalFileHandleId + "/copy"; S3FileHandle changes = new S3FileHandle(); changes.setFileName(name); changes.setContentType(contentType); return doCreateJSONEntity(getFileEndpoint(), uri, changes); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#startBulkFileDownload(org.sagebionetworks.repo.model.file.BulkFileDownloadRequest) */ @Override public String startBulkFileDownload(BulkFileDownloadRequest request) throws SynapseException{ return startAsynchJob(AsynchJobType.BulkFileDownload, request); } @Override public BulkFileDownloadResponse getBulkFileDownloadResults(String asyncJobToken) throws SynapseException, SynapseResultNotReadyException { return (BulkFileDownloadResponse) getAsyncResult(AsynchJobType.BulkFileDownload, asyncJobToken, (String) null); } /** * Asymmetrical post where the request and response are not of the same * type. * * @param url * @param reqeust * @param calls * @throws SynapseException */ private <T extends JSONEntity> T asymmetricalPost(String endpoint, String url, JSONEntity requestBody, Class<? extends T> returnClass, SharedClientConnection.ErrorHandler errorHandler) throws SynapseException { try { String jsonString = EntityFactory .createJSONStringForEntity(requestBody); JSONObject responseBody = getSharedClientConnection().postJson( endpoint, url, jsonString, getUserAgent(), null, errorHandler); return EntityFactory.createEntityFromJSONObject(responseBody, returnClass); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Asymmetrical put where the request and response are not of the same * type. * * @param url * @param reqeust * @param calls * @throws SynapseException */ private <T extends JSONEntity> T asymmetricalPut(String endpoint, String url, JSONEntity requestBody, Class<? extends T> returnClass) throws SynapseException { try { String jsonString = null; if(requestBody != null){ jsonString = EntityFactory .createJSONStringForEntity(requestBody); } JSONObject responseBody = getSharedClientConnection().putJson( endpoint, url, jsonString, getUserAgent()); return EntityFactory.createEntityFromJSONObject(responseBody, returnClass); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get the raw file handle. Note: Only the creator of a the file handle can * get the raw file handle. * * @param fileHandleId * @return * @throws SynapseException */ @Override public FileHandle getRawFileHandle(String fileHandleId) throws SynapseException { JSONObject object = getSharedClientConnection().getJson( getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId, getUserAgent()); try { return EntityFactory.createEntityFromJSONObject(object, FileHandle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Delete a raw file handle. Note: Only the creator of a the file handle can * delete the file handle. * * @param fileHandleId * @throws SynapseException */ @Override public void deleteFileHandle(String fileHandleId) throws SynapseException { getSharedClientConnection().deleteUri(getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId, getUserAgent()); } /** * Delete the preview associated with the given file handle. Note: Only the * creator of a the file handle can delete the preview. * * @param fileHandleId * @throws SynapseException */ @Override public void clearPreview(String fileHandleId) throws SynapseException { getSharedClientConnection() .deleteUri(getFileEndpoint(), FILE_HANDLE + "/" + fileHandleId + FILE_PREVIEW, getUserAgent()); } /** * Guess the content type of a file by reading the start of the file stream * using URLConnection.guessContentTypeFromStream(is); If URLConnection * fails to return a content type then "application/octet-stream" will be * returned. * * @param file * @return * @throws FileNotFoundException * @throws IOException */ public static String guessContentTypeFromStream(File file) throws FileNotFoundException, IOException { InputStream is = new BufferedInputStream(new FileInputStream(file)); try { // Let java guess from the stream. String contentType = URLConnection.guessContentTypeFromStream(is); // If Java fails then set the content type to be octet-stream if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } return contentType; } finally { is.close(); } } /** * * Create a wiki page for a given owner object. * * @param ownerId * @param ownerType * @param toCreate * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public WikiPage createWikiPage(String ownerId, ObjectType ownerType, WikiPage toCreate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toCreate == null) throw new IllegalArgumentException("WikiPage cannot be null"); String uri = createWikiURL(ownerId, ownerType); return doCreateJSONEntity(uri, toCreate); } /** * Helper to create a wiki URL that does not include the wiki id. * * @param ownerId * @param ownerType * @return */ private String createWikiURL(String ownerId, ObjectType ownerType) { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); return String.format(WIKI_URI_TEMPLATE, ownerType.name().toLowerCase(), ownerId); } /** * Get a WikiPage using its key * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public WikiPage getWikiPage(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key); return getJSONEntity(uri, WikiPage.class); } @Override public WikiPage getWikiPageForVersion(WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { String uri = createWikiURL(key) + VERSION_PARAMETER + version; return getJSONEntity(uri, WikiPage.class); } @Override public WikiPageKey getRootWikiPageKey(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createWikiURL(ownerId, ownerType)+"key"; return getJSONEntity(uri, WikiPageKey.class); } /** * Get a the root WikiPage for a given owner. * * @param ownerId * @param ownerType * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public WikiPage getRootWikiPage(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createWikiURL(ownerId, ownerType); return getJSONEntity(uri, WikiPage.class); } /** * Get all of the FileHandles associated with a WikiPage, including any * PreviewHandles. * * @param key * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getWikiAttachmenthHandles(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key) + ATTACHMENT_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } private static String createWikiAttachmentURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createWikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a WikiPage attachment. This is an alternative * to downloading the attachment to a file. * * @param key * - Identifies a wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getWikiAttachmentTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createWikiAttachmentURI(key, fileName, false)); } @Override public void downloadWikiAttachment(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createWikiAttachmentURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createWikiAttachmentPreviewURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createWikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a WikiPage attachment preview. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getWikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createWikiAttachmentPreviewURI(key, fileName, false)); } @Override public void downloadWikiAttachmentPreview(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createWikiAttachmentPreviewURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for the current * version of the entity.. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityTemporaryUrlForCurrentVersion(String entityId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityCurrentVersion(String fileEntityId, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + fileEntityId + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file preview of a FileEntity for the * current version of the entity.. This is an alternative to downloading the * file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityPreviewTemporaryUrlForCurrentVersion(String entityId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityPreviewCurrentVersion( String fileEntityId, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + fileEntityId + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for a given * version number. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityTemporaryUrlForVersion(String entityId, Long versionNumber) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityForVersion(String entityId, Long versionNumber, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Get the temporary URL for the data file of a FileEntity for a given * version number. This is an alternative to downloading the file. * * @param entityId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileEntityPreviewTemporaryUrlForVersion(String entityId, Long versionNumber) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromFileEntityPreviewForVersion(String entityId, Long versionNumber, File destinationFile) throws SynapseException { String uri = ENTITY + "/" + entityId + VERSION_INFO + "/" + versionNumber + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } /** * Fetch a temporary url. * * @param uri * @return * @throws ClientProtocolException * @throws IOException * @throws MalformedURLException * @throws SynapseException */ private URL getUrl(String uri) throws ClientProtocolException, IOException, MalformedURLException, SynapseException { return new URL(getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent())); } private URL getUrl(String endpoint, String uri) throws ClientProtocolException, IOException, MalformedURLException, SynapseException { return new URL(getSharedClientConnection().getDirect(endpoint, uri, getUserAgent())); } /** * Update a WikiPage * * @param ownerId * @param ownerType * @param toUpdate * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public WikiPage updateWikiPage(String ownerId, ObjectType ownerType, WikiPage toUpdate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toUpdate == null) throw new IllegalArgumentException("WikiPage cannot be null"); if (toUpdate.getId() == null) throw new IllegalArgumentException( "WikiPage.getId() cannot be null"); String uri = String.format(WIKI_ID_URI_TEMPLATE, ownerType.name() .toLowerCase(), ownerId, toUpdate.getId()); return updateJSONEntity(uri, toUpdate); } /** * Delete a WikiPage * * @param key * @throws SynapseException */ @Override public void deleteWikiPage(WikiPageKey key) throws SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createWikiURL(key); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Helper to build a URL for a wiki page. * * @param key * @return */ private static String createWikiURL(WikiPageKey key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); return String.format(WIKI_ID_URI_TEMPLATE, key.getOwnerObjectType() .name().toLowerCase(), key.getOwnerObjectId(), key.getWikiPageId()); } /** * Get the WikiHeader tree for a given owner object. * * @param ownerId * @param ownerType * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<WikiHeader> getWikiHeaderTree(String ownerId, ObjectType ownerType) throws SynapseException, JSONObjectAdapterException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = String.format(WIKI_TREE_URI_TEMPLATE, ownerType.name() .toLowerCase(), ownerId); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<WikiHeader> paginated = new PaginatedResults<WikiHeader>( WikiHeader.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } /** * Get the file handles for the current version of an entity. * * @param entityId * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getEntityFileHandlesForCurrentVersion( String entityId) throws JSONObjectAdapterException, SynapseException { if (entityId == null) throw new IllegalArgumentException("Key cannot be null"); String uri = ENTITY_URI_PATH + "/" + entityId + FILE_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } /** * Get the file hanldes for a given version of an entity. * * @param entityId * @param versionNumber * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getEntityFileHandlesForVersion(String entityId, Long versionNumber) throws JSONObjectAdapterException, SynapseException { if (entityId == null) throw new IllegalArgumentException("Key cannot be null"); String uri = ENTITY_URI_PATH + "/" + entityId + "/version/" + versionNumber + FILE_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } // V2 WIKIPAGE METHODS /** * Helper to create a V2 Wiki URL (No ID) */ private String createV2WikiURL(String ownerId, ObjectType ownerType) { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); return String.format(WIKI_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId); } /** * Helper to build a URL for a V2 Wiki page, with ID * * @param key * @return */ private static String createV2WikiURL(WikiPageKey key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); return String.format(WIKI_ID_URI_TEMPLATE_V2, key.getOwnerObjectType() .name().toLowerCase(), key.getOwnerObjectId(), key.getWikiPageId()); } /** * * Create a V2 WikiPage for a given owner object. * * @param ownerId * @param ownerType * @param toCreate * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public V2WikiPage createV2WikiPage(String ownerId, ObjectType ownerType, V2WikiPage toCreate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toCreate == null) throw new IllegalArgumentException("WikiPage cannot be null"); String uri = createV2WikiURL(ownerId, ownerType); return doCreateJSONEntity(uri, toCreate); } /** * Get a V2 WikiPage using its key * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public V2WikiPage getV2WikiPage(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key); return getJSONEntity(uri, V2WikiPage.class); } /** * Get a version of a V2 WikiPage using its key and version number */ @Override public V2WikiPage getVersionOfV2WikiPage(WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + VERSION_PARAMETER + version; return getJSONEntity(uri, V2WikiPage.class); } /** * Get a the root V2 WikiPage for a given owner. * * @param ownerId * @param ownerType * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage getV2RootWikiPage(String ownerId, ObjectType ownerType) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = createV2WikiURL(ownerId, ownerType); return getJSONEntity(uri, V2WikiPage.class); } /** * Update a V2 WikiPage * * @param ownerId * @param ownerType * @param toUpdate * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage updateV2WikiPage(String ownerId, ObjectType ownerType, V2WikiPage toUpdate) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (toUpdate == null) throw new IllegalArgumentException("WikiPage cannot be null"); if (toUpdate.getId() == null) throw new IllegalArgumentException( "WikiPage.getId() cannot be null"); String uri = String.format(WIKI_ID_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId, toUpdate.getId()); return updateJSONEntity(uri, toUpdate); } @Override public V2WikiOrderHint updateV2WikiOrderHint(V2WikiOrderHint toUpdate) throws JSONObjectAdapterException, SynapseException { if (toUpdate == null) throw new IllegalArgumentException("toUpdate cannot be null"); if (toUpdate.getOwnerId() == null) throw new IllegalArgumentException( "V2WikiOrderHint.getOwnerId() cannot be null"); if (toUpdate.getOwnerObjectType() == null) throw new IllegalArgumentException( "V2WikiOrderHint.getOwnerObjectType() cannot be null"); String uri = String.format(WIKI_ORDER_HINT_URI_TEMPLATE_V2, toUpdate .getOwnerObjectType().name().toLowerCase(), toUpdate.getOwnerId()); return updateJSONEntity(uri, toUpdate); } /** * Restore contents of a V2 WikiPage to the contents of a particular * version. * * @param ownerId * @param ownerType * @param wikiId * @param versionToRestore * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public V2WikiPage restoreV2WikiPage(String ownerId, ObjectType ownerType, String wikiId, Long versionToRestore) throws JSONObjectAdapterException, SynapseException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); if (wikiId == null) throw new IllegalArgumentException("Wiki id cannot be null"); if (versionToRestore == null) throw new IllegalArgumentException("Version cannot be null"); String uri = String.format(WIKI_ID_VERSION_URI_TEMPLATE_V2, ownerType .name().toLowerCase(), ownerId, wikiId, String .valueOf(versionToRestore)); V2WikiPage mockWikiToUpdate = new V2WikiPage(); return updateJSONEntity(uri, mockWikiToUpdate); } /** * Get all of the FileHandles associated with a V2 WikiPage, including any * PreviewHandles. * * @param key * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @Override public FileHandleResults getV2WikiAttachmentHandles(WikiPageKey key) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + ATTACHMENT_HANDLES; return getJSONEntity(uri, FileHandleResults.class); } @Override public FileHandleResults getVersionOfV2WikiAttachmentHandles( WikiPageKey key, Long version) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + ATTACHMENT_HANDLES + VERSION_PARAMETER + version; return getJSONEntity(uri, FileHandleResults.class); } @Override public String downloadV2WikiMarkdown(WikiPageKey key) throws ClientProtocolException, FileNotFoundException, IOException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + MARKDOWN_FILE; return getSharedClientConnection().downloadZippedFileString( repoEndpoint, uri, getUserAgent()); } @Override public String downloadVersionOfV2WikiMarkdown(WikiPageKey key, Long version) throws ClientProtocolException, FileNotFoundException, IOException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (version == null) throw new IllegalArgumentException("Version cannot be null"); String uri = createV2WikiURL(key) + MARKDOWN_FILE + VERSION_PARAMETER + version; return getSharedClientConnection().downloadZippedFileString( repoEndpoint, uri, getUserAgent()); } private static String createV2WikiAttachmentURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a V2 WikiPage attachment. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a V2 wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getV2WikiAttachmentTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createV2WikiAttachmentURI(key, fileName, false)); } @Override public void downloadV2WikiAttachment(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createV2WikiAttachmentURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createV2WikiAttachmentPreviewURI(WikiPageKey key, String fileName, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect; } /** * Get the temporary URL for a V2 WikiPage attachment preview. This is an * alternative to downloading the attachment to a file. * * @param key * - Identifies a V2 wiki page. * @param fileName * - The name of the attachment file. * @return * @throws IOException * @throws ClientProtocolException * @throws SynapseException */ @Override public URL getV2WikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName) throws ClientProtocolException, IOException, SynapseException { return getUrl(createV2WikiAttachmentPreviewURI(key, fileName, false)); } @Override public void downloadV2WikiAttachmentPreview(WikiPageKey key, String fileName, File target) throws SynapseException { String uri = createV2WikiAttachmentPreviewURI(key, fileName, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createVersionOfV2WikiAttachmentPreviewURI( WikiPageKey key, String fileName, Long version, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE_PREVIEW + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect + AND_VERSION_PARAMETER + version; } @Override public URL getVersionOfV2WikiAttachmentPreviewTemporaryUrl(WikiPageKey key, String fileName, Long version) throws ClientProtocolException, IOException, SynapseException { return getUrl(createVersionOfV2WikiAttachmentPreviewURI(key, fileName, version, false)); } @Override public void downloadVersionOfV2WikiAttachmentPreview(WikiPageKey key, String fileName, Long version, File target) throws SynapseException { String uri = createVersionOfV2WikiAttachmentPreviewURI(key, fileName, version, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } private static String createVersionOfV2WikiAttachmentURI(WikiPageKey key, String fileName, Long version, boolean redirect) throws SynapseClientException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (fileName == null) throw new IllegalArgumentException("fileName cannot be null"); String encodedName; try { encodedName = URLEncoder.encode(fileName, "UTF-8"); } catch (IOException e) { throw new SynapseClientException("Failed to encode " + fileName, e); } return createV2WikiURL(key) + ATTACHMENT_FILE + FILE_NAME_PARAMETER + encodedName + AND_REDIRECT_PARAMETER + redirect + AND_VERSION_PARAMETER + version; } @Override public URL getVersionOfV2WikiAttachmentTemporaryUrl(WikiPageKey key, String fileName, Long version) throws ClientProtocolException, IOException, SynapseException { return getUrl(createVersionOfV2WikiAttachmentURI(key, fileName, version, false)); } // alternative to getVersionOfV2WikiAttachmentTemporaryUrl @Override public void downloadVersionOfV2WikiAttachment(WikiPageKey key, String fileName, Long version, File target) throws SynapseException { String uri = createVersionOfV2WikiAttachmentURI(key, fileName, version, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Delete a V2 WikiPage * * @param key * @throws SynapseException */ @Override public void deleteV2WikiPage(WikiPageKey key) throws SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public V2WikiPage deleteV2WikiVersions(WikiPageKey key, WikiVersionsList versionsToDelete) throws SynapseException, JSONObjectAdapterException { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } if (versionsToDelete == null) { throw new IllegalArgumentException("VersionsToDelete cannot be null"); } String uri = createV2WikiURL(key) + "/markdown/deleteversion"; String postJSON = EntityFactory.createJSONStringForEntity(versionsToDelete); JSONObject jsonObject = getSharedClientConnection().putJson(repoEndpoint, uri, postJSON, getUserAgent()); return EntityFactory.createEntityFromJSONObject(jsonObject, V2WikiPage.class); } /** * Get the WikiHeader tree for a given owner object. * * @param ownerId * @param ownerType * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<V2WikiHeader> getV2WikiHeaderTree(String ownerId, ObjectType ownerType) throws SynapseException, JSONObjectAdapterException { if (ownerId == null) throw new IllegalArgumentException("ownerId cannot be null"); if (ownerType == null) throw new IllegalArgumentException("ownerType cannot be null"); String uri = String.format(WIKI_TREE_URI_TEMPLATE_V2, ownerType.name() .toLowerCase(), ownerId); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<V2WikiHeader> paginated = new PaginatedResults<V2WikiHeader>( V2WikiHeader.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } @Override public V2WikiOrderHint getV2OrderHint(WikiPageKey key) throws SynapseException, JSONObjectAdapterException { if (key == null) throw new IllegalArgumentException("key cannot be null"); String uri = String.format(WIKI_ORDER_HINT_URI_TEMPLATE_V2, key .getOwnerObjectType().name().toLowerCase(), key.getOwnerObjectId()); JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); V2WikiOrderHint orderHint = new V2WikiOrderHint(); orderHint.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return orderHint; } /** * Get the tree of snapshots (outlining each modification) for a particular * V2 WikiPage * * @param key * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public PaginatedResults<V2WikiHistorySnapshot> getV2WikiHistory( WikiPageKey key, Long limit, Long offset) throws JSONObjectAdapterException, SynapseException { if (key == null) throw new IllegalArgumentException("Key cannot be null"); String uri = createV2WikiURL(key) + WIKI_HISTORY_V2 + "?" + OFFSET_PARAMETER + offset + AND_LIMIT_PARAMETER + limit; JSONObject object = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<V2WikiHistorySnapshot> paginated = new PaginatedResults<V2WikiHistorySnapshot>( V2WikiHistorySnapshot.class); paginated.initializeFromJSONObject(new JSONObjectAdapterImpl(object)); return paginated; } public File downloadFromSynapse(String path, String md5, File destinationFile) throws SynapseException { return getSharedClientConnection().downloadFromSynapse(path, md5, destinationFile, null); } /******************** Low Level APIs ********************/ /** * Create any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") <T extends JSONEntity> T doCreateJSONEntity(String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String postJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().postJson( repoEndpoint, uri, postJSON, getUserAgent(), null); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Create any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") private <T extends JSONEntity> T doCreateJSONEntity(String endpoint, String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String postJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().postJson(endpoint, uri, postJSON, getUserAgent(), null); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Update any JSONEntity * * @param endpoint * @param uri * @param entity * @return * @throws JSONObjectAdapterException * @throws SynapseException */ @SuppressWarnings("unchecked") private <T extends JSONEntity> T updateJSONEntity(String uri, T entity) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == entity) { throw new IllegalArgumentException("must provide entity"); } String putJSON = EntityFactory.createJSONStringForEntity(entity); JSONObject jsonObject = getSharedClientConnection().putJson( repoEndpoint, uri, putJSON, getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, entity.getClass()); } /** * Get a JSONEntity */ protected <T extends JSONEntity> T getJSONEntity(String uri, Class<? extends T> clazz) throws JSONObjectAdapterException, SynapseException { if (null == uri) { throw new IllegalArgumentException("must provide uri"); } if (null == clazz) { throw new IllegalArgumentException("must provide entity"); } JSONObject jsonObject = getSharedClientConnection().getJson( repoEndpoint, uri, getUserAgent()); return (T) EntityFactory.createEntityFromJSONObject(jsonObject, clazz); } /** * Get a dataset, layer, preview, annotations, etc... * * @return the retrieved entity */ private JSONObject getSynapseEntity(String endpoint, String uri) throws SynapseException { if (null == endpoint) { throw new IllegalArgumentException("must provide endpoint"); } if (null == uri) { throw new IllegalArgumentException("must provide uri"); } return getSharedClientConnection().getJson(endpoint, uri, getUserAgent()); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#startAsynchJob(org.sagebionetworks.client.AsynchJobType, org.sagebionetworks.repo.model.asynch.AsynchronousRequestBody) */ public String startAsynchJob(AsynchJobType type, AsynchronousRequestBody request) throws SynapseException { String url = type.getStartUrl(request); String endpoint = getEndpointForType(type.getRestEndpoint()); AsyncJobId jobId = asymmetricalPost(endpoint, url, request, AsyncJobId.class, null); return jobId.getToken(); } @Override public void cancelAsynchJob(String jobId) throws SynapseException { String url = ASYNCHRONOUS_JOB + "/" + jobId + "/cancel"; getSharedClientConnection().getJson(getRepoEndpoint(), url, getUserAgent()); } @Override public AsynchronousResponseBody getAsyncResult(AsynchJobType type, String jobId, AsynchronousRequestBody request) throws SynapseException, SynapseClientException, SynapseResultNotReadyException { String url = type.getResultUrl(jobId, request); String endpoint = getEndpointForType(type.getRestEndpoint()); return getAsynchJobResponse(url, type.getReponseClass(), endpoint); } @Override public AsynchronousResponseBody getAsyncResult(AsynchJobType type, String jobId, String entityId) throws SynapseException, SynapseClientException, SynapseResultNotReadyException { String url = type.getResultUrl(jobId, entityId); String endpoint = getEndpointForType(type.getRestEndpoint()); return getAsynchJobResponse(url, type.getReponseClass(), endpoint); } /** * Get a job response body for a url. * @param url * @param clazz * @return * @throws SynapseException */ private AsynchronousResponseBody getAsynchJobResponse(String url, Class<? extends AsynchronousResponseBody> clazz, String endpoint) throws SynapseException { JSONObject responseBody = getSharedClientConnection().getJson( endpoint, url, getUserAgent(), new SharedClientConnection.ErrorHandler() { @Override public void handleError(int code, String responseBody) throws SynapseException { if (code == HttpStatus.SC_ACCEPTED) { try { AsynchronousJobStatus status = EntityFactory .createEntityFromJSONString( responseBody, AsynchronousJobStatus.class); throw new SynapseResultNotReadyException( status); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e .getMessage(), e); } } } }); try { return EntityFactory.createEntityFromJSONObject(responseBody, clazz); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Update a dataset, layer, preview, annotations, etc... * * This convenience method first grabs a copy of the currently stored * entity, then overwrites fields from the entity passed in on top of the * stored entity we retrieved and then PUTs the entity. This essentially * does a partial update from the point of view of the user of this API. * * Note that users of this API may want to inspect what they are overwriting * before they do so. Another approach would be to do a GET, display the * field to the user, allow them to edit the fields, and then do a PUT. * * @param defaultEndpoint * @param uri * @param entity * @return the updated entity * @throws SynapseException */ @SuppressWarnings("unchecked") @Deprecated public JSONObject updateSynapseEntity(String uri, JSONObject entity) throws SynapseException { JSONObject storedEntity = getSharedClientConnection().getJson( repoEndpoint, uri, getUserAgent()); boolean isAnnotation = uri.endsWith(ANNOTATION_URI_SUFFIX); try { Iterator<String> keyIter = entity.keys(); while (keyIter.hasNext()) { String key = keyIter.next(); if (isAnnotation) { // Annotations need to go one level deeper JSONObject storedAnnotations = storedEntity .getJSONObject(key); JSONObject entityAnnotations = entity.getJSONObject(key); Iterator<String> annotationIter = entity.getJSONObject(key) .keys(); while (annotationIter.hasNext()) { String annotationKey = annotationIter.next(); storedAnnotations.put(annotationKey, entityAnnotations.get(annotationKey)); } } else { storedEntity.put(key, entity.get(key)); } } return getSharedClientConnection().putJson(repoEndpoint, uri, storedEntity.toString(), getUserAgent()); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Perform a query * * @param query * the query to perform * @return the query result */ private JSONObject querySynapse(String query) throws SynapseException { try { if (null == query) { throw new IllegalArgumentException("must provide a query"); } String queryUri; queryUri = QUERY_URI + URLEncoder.encode(query, "UTF-8"); return getSharedClientConnection().getJson(repoEndpoint, queryUri, getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } /** * @return status * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public StackStatus getCurrentStackStatus() throws SynapseException, JSONObjectAdapterException { JSONObject json = getEntity(STACK_STATUS); return EntityFactory .createEntityFromJSONObject(json, StackStatus.class); } @Override public SearchResults search(SearchQuery searchQuery) throws SynapseException, UnsupportedEncodingException, JSONObjectAdapterException { SearchResults searchResults = null; String uri = "/search"; String jsonBody = EntityFactory.createJSONStringForEntity(searchQuery); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); if (obj != null) { JSONObjectAdapter adapter = new JSONObjectAdapterImpl(obj); searchResults = new SearchResults(adapter); } return searchResults; } @Override public String getSynapseTermsOfUse() throws SynapseException { return getTermsOfUse(DomainType.SYNAPSE); } @Override public String getTermsOfUse(DomainType domain) throws SynapseException { if (domain == null) { throw new IllegalArgumentException("Domain must be specified"); } return getHttpClientHelper().getDataDirect(authEndpoint, "/" + domain.name().toLowerCase() + "TermsOfUse.html"); } /** * Helper for pagination of messages */ private String setMessageParameters(String path, List<MessageStatusType> inboxFilter, MessageSortBy orderBy, Boolean descending, Long limit, Long offset) { if (path == null) { throw new IllegalArgumentException("Path must be specified"); } URIBuilder builder = new URIBuilder(); builder.setPath(path); if (inboxFilter != null) { builder.setParameter(MESSAGE_INBOX_FILTER_PARAM, StringUtils.join(inboxFilter.toArray(), ',')); } if (orderBy != null) { builder.setParameter(MESSAGE_ORDER_BY_PARAM, orderBy.name()); } if (descending != null) { builder.setParameter(MESSAGE_DESCENDING_PARAM, "" + descending); } if (limit != null) { builder.setParameter(LIMIT, "" + limit); } if (offset != null) { builder.setParameter(OFFSET, "" + offset); } return builder.toString(); } @Override public MessageToUser sendMessage(MessageToUser message) throws SynapseException { String uri = MESSAGE; try { String jsonBody = EntityFactory.createJSONStringForEntity(message); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#uploadToFileHandle(byte[], org.apache.http.entity.ContentType, java.lang.String) */ @Override public String uploadToFileHandle(byte[] content, ContentType contentType, String parentEntityId) throws SynapseException { List<UploadDestination> uploadDestinations = getUploadDestinations(parentEntityId); if (uploadDestinations.isEmpty()) { // default to S3 return uploadToS3FileHandle(content, contentType, null); } UploadDestination uploadDestination = uploadDestinations.get(0); switch (uploadDestination.getUploadType()) { case HTTPS: case SFTP: throw new NotImplementedException( "SFTP and HTTPS uploads not implemented yet"); case S3: return uploadToS3FileHandle(content, contentType, (S3UploadDestination) uploadDestination); default: throw new NotImplementedException(uploadDestination.getUploadType() .name() + " uploads not implemented yet"); } } /** * uploads a String to S3 using the chunked file upload service * * @param content * the content to upload. Strings in memory should not be large, * so we limit to the size of one 'chunk' * @param contentType * should include the character encoding, e.g. * "text/plain; charset=utf-8" */ @Override public String uploadToFileHandle(byte[] content, ContentType contentType) throws SynapseException { return uploadToS3FileHandle(content, contentType, null); } /** * uploads a String to S3 using the chunked file upload service * * @param content * the content to upload. Strings in memory should not be large, * so we limit to the size of one 'chunk' * @param contentType * should include the character encoding, e.g. * "text/plain; charset=utf-8" */ private String uploadToS3FileHandle(byte[] content, ContentType contentType, UploadDestination uploadDestination) throws SynapseClientException, SynapseException { if (content == null || content.length == 0) throw new IllegalArgumentException("Missing content."); if (content.length >= MINIMUM_CHUNK_SIZE_BYTES) throw new IllegalArgumentException("String must be less than " + MINIMUM_CHUNK_SIZE_BYTES + " bytes."); String contentMD5 = null; try { contentMD5 = MD5ChecksumHelper.getMD5ChecksumForByteArray(content); } catch (IOException e) { throw new SynapseClientException(e); } CreateChunkedFileTokenRequest ccftr = new CreateChunkedFileTokenRequest(); ccftr.setFileName("content"); ccftr.setContentType(contentType.toString()); ccftr.setContentMD5(contentMD5); ccftr.setUploadDestination(uploadDestination); ccftr.setStorageLocationId(uploadDestination == null ? null : uploadDestination.getStorageLocationId()); // Start the upload ChunkedFileToken token = createChunkedFileUploadToken(ccftr); // because of the restriction on string length there will be exactly one // chunk List<Long> chunkNumbers = new ArrayList<Long>(); long currentChunkNumber = 1; chunkNumbers.add(currentChunkNumber); ChunkRequest request = new ChunkRequest(); request.setChunkedFileToken(token); request.setChunkNumber((long) currentChunkNumber); URL presignedURL = createChunkedPresignedUrl(request); getHttpClientHelper().putBytesToURL(presignedURL, content, contentType.toString()); CompleteAllChunksRequest cacr = new CompleteAllChunksRequest(); cacr.setChunkedFileToken(token); cacr.setChunkNumbers(chunkNumbers); UploadDaemonStatus status = startUploadDeamon(cacr); State state = status.getState(); if (state.equals(State.FAILED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); long backOffMillis = 100L; // initially just 1/10 sec, but will // exponentially increase while (state.equals(State.PROCESSING) && backOffMillis <= MAX_BACKOFF_MILLIS) { try { Thread.sleep(backOffMillis); } catch (InterruptedException e) { // continue } status = getCompleteUploadDaemonStatus(status.getDaemonId()); state = status.getState(); if (state.equals(State.FAILED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); backOffMillis *= 2; // exponential backoff } if (!state.equals(State.COMPLETED)) throw new IllegalStateException("Message creation failed: " + status.getErrorMessage()); return status.getFileHandleId(); } private static final ContentType STRING_MESSAGE_CONTENT_TYPE = ContentType .create("text/plain", MESSAGE_CHARSET); /** * Convenience function to upload a simple string message body, then send * message using resultant fileHandleId * * @param message * @param messageBody * @return the created message * @throws SynapseException */ @Override public MessageToUser sendStringMessage(MessageToUser message, String messageBody) throws SynapseException { if (message.getFileHandleId() != null) throw new IllegalArgumentException( "Expected null fileHandleId but found " + message.getFileHandleId()); String fileHandleId = uploadToFileHandle( messageBody.getBytes(MESSAGE_CHARSET), STRING_MESSAGE_CONTENT_TYPE); message.setFileHandleId(fileHandleId); return sendMessage(message); } /** * Convenience function to upload a simple string message body, then send * message to entity owner using resultant fileHandleId * * @param message * @param entityId * @param messageBody * @return the created message * @throws SynapseException */ @Override public MessageToUser sendStringMessage(MessageToUser message, String entityId, String messageBody) throws SynapseException { if (message.getFileHandleId() != null) throw new IllegalArgumentException( "Expected null fileHandleId but found " + message.getFileHandleId()); String fileHandleId = uploadToFileHandle( messageBody.getBytes(MESSAGE_CHARSET), STRING_MESSAGE_CONTENT_TYPE); message.setFileHandleId(fileHandleId); return sendMessage(message, entityId); } @Override public MessageToUser sendMessage(MessageToUser message, String entityId) throws SynapseException { String uri = ENTITY + "/" + entityId + "/" + MESSAGE; try { String jsonBody = EntityFactory.createJSONStringForEntity(message); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageBundle> getInbox( List<MessageStatusType> inboxFilter, MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE_INBOX, inboxFilter, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageBundle> messages = new PaginatedResults<MessageBundle>( MessageBundle.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageToUser> getOutbox(MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE_OUTBOX, null, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageToUser> messages = new PaginatedResults<MessageToUser>( MessageToUser.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MessageToUser getMessage(String messageId) throws SynapseException { String uri = MESSAGE + "/" + messageId; try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MessageToUser forwardMessage(String messageId, MessageRecipientSet recipients) throws SynapseException { String uri = MESSAGE + "/" + messageId + FORWARD; try { String jsonBody = EntityFactory .createJSONStringForEntity(recipients); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, MessageToUser.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MessageToUser> getConversation( String associatedMessageId, MessageSortBy orderBy, Boolean descending, long limit, long offset) throws SynapseException { String uri = setMessageParameters(MESSAGE + "/" + associatedMessageId + CONVERSATION, null, orderBy, descending, limit, offset); try { JSONObject obj = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); PaginatedResults<MessageToUser> messages = new PaginatedResults<MessageToUser>( MessageToUser.class); messages.initializeFromJSONObject(new JSONObjectAdapterImpl(obj)); return messages; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateMessageStatus(MessageStatus status) throws SynapseException { String uri = MESSAGE_STATUS; try { String jsonBody = EntityFactory.createJSONStringForEntity(status); getSharedClientConnection().putJson(repoEndpoint, uri, jsonBody, getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMessage(String messageId) throws SynapseException { String uri = MESSAGE + "/" + messageId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } private static String createDownloadMessageURI(String messageId, boolean redirect) { return MESSAGE + "/" + messageId + FILE + "?" + REDIRECT_PARAMETER + redirect; } @Override public String getMessageTemporaryUrl(String messageId) throws SynapseException, MalformedURLException, IOException { String uri = createDownloadMessageURI(messageId, false); return getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent()); } @Override public String downloadMessage(String messageId) throws SynapseException, MalformedURLException, IOException { String uri = createDownloadMessageURI(messageId, true); return getSharedClientConnection().getDirect(repoEndpoint, uri, getUserAgent()); } @Override public void downloadMessageToFile(String messageId, File target) throws SynapseException { String uri = createDownloadMessageURI(messageId, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } /** * Get the child count for this entity * * @param entityId * @return * @throws SynapseException * @throws JSONException */ @Override public Long getChildCount(String entityId) throws SynapseException { String queryString = SELECT_ID_FROM_ENTITY_WHERE_PARENT_ID + entityId + LIMIT_1_OFFSET_1; JSONObject query = query(queryString); if (!query.has(TOTAL_NUM_RESULTS)) { throw new SynapseClientException("Query results did not have " + TOTAL_NUM_RESULTS); } try { return query.getLong(TOTAL_NUM_RESULTS); } catch (JSONException e) { throw new SynapseClientException(e); } } /** * Get the appropriate piece of the URL based on the attachment type * * @param type * @return */ public static String getAttachmentTypeURL( ServiceConstants.AttachmentType type) { if (type == AttachmentType.ENTITY) return ENTITY; else if (type == AttachmentType.USER_PROFILE) return USER_PROFILE_PATH; else throw new IllegalArgumentException("Unrecognized attachment type: " + type); } /** * Get the ids of all users and groups. * * @param client * @return * @throws SynapseException */ @Override public Set<String> getAllUserAndGroupIds() throws SynapseException { HashSet<String> ids = new HashSet<String>(); // Get all the users PaginatedResults<UserProfile> pr = this.getUsers(0, Integer.MAX_VALUE); for (UserProfile up : pr.getResults()) { ids.add(up.getOwnerId()); } PaginatedResults<UserGroup> groupPr = this.getGroups(0, Integer.MAX_VALUE); for (UserGroup ug : groupPr.getResults()) { ids.add(ug.getId()); } return ids; } /** * @return version * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public SynapseVersionInfo getVersionInfo() throws SynapseException, JSONObjectAdapterException { JSONObject json = getEntity(VERSION_INFO); return EntityFactory.createEntityFromJSONObject(json, SynapseVersionInfo.class); } /** * Get the activity generatedBy an Entity * * @param entityId * @return * @throws SynapseException */ @Override public Activity getActivityForEntity(String entityId) throws SynapseException { return getActivityForEntityVersion(entityId, null); } /** * Get the activity generatedBy an Entity * * @param entityId * @param versionNumber * @return * @throws SynapseException */ @Override public Activity getActivityForEntityVersion(String entityId, Long versionNumber) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("EntityId cannot be null"); String url = createEntityUri(ENTITY_URI_PATH, entityId); if (versionNumber != null) { url += REPO_SUFFIX_VERSION + "/" + versionNumber; } url += GENERATED_BY_SUFFIX; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Activity(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Set the activity generatedBy an Entity * * @param entityId * @param activityId * @return * @throws SynapseException */ @Override public Activity setActivityForEntity(String entityId, String activityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ENTITY_URI_PATH, entityId) + GENERATED_BY_SUFFIX; if (activityId != null) url += "?" + PARAM_GENERATED_BY + "=" + activityId; try { JSONObject jsonObject = new JSONObject(); // no need for a body jsonObject = getSharedClientConnection().putJson(repoEndpoint, url, jsonObject.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); return new Activity(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Delete the generatedBy relationship for an Entity (does not delete the * activity) * * @param entityId * @throws SynapseException */ @Override public void deleteGeneratedByForEntity(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String uri = createEntityUri(ENTITY_URI_PATH, entityId) + GENERATED_BY_SUFFIX; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Create an activity * * @param activity * @return * @throws SynapseException */ @Override public Activity createActivity(Activity activity) throws SynapseException { if (activity == null) throw new IllegalArgumentException("Activity can not be null"); String url = ACTIVITY_URI_PATH; JSONObjectAdapter toCreateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(activity.writeToJSONObject(toCreateAdapter) .toJSONString()); JSONObject jsonObj = createJSONObject(url, obj); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Activity(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Get activity by id * * @param activityId * @return * @throws SynapseException */ @Override public Activity getActivity(String activityId) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activityId); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Activity(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Update an activity * * @param activity * @return * @throws SynapseException */ @Override public Activity putActivity(Activity activity) throws SynapseException { if (activity == null) throw new IllegalArgumentException("Activity can not be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activity.getId()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(activity.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Activity(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Delete an activity. This will remove all generatedBy connections to this * activity as well. * * @param activityId * @throws SynapseException */ @Override public void deleteActivity(String activityId) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String uri = createEntityUri(ACTIVITY_URI_PATH, activityId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public PaginatedResults<Reference> getEntitiesGeneratedBy( String activityId, Integer limit, Integer offset) throws SynapseException { if (activityId == null) throw new IllegalArgumentException("Activity id cannot be null"); String url = createEntityUri(ACTIVITY_URI_PATH, activityId + GENERATED_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Reference> results = new PaginatedResults<Reference>( Reference.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation createEvaluation(Evaluation eval) throws SynapseException { String uri = EVALUATION_URI_PATH; try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(eval); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Evaluation.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation getEvaluation(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = createEntityUri(EVALUATION_URI_PATH, evalId); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Evaluation(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public PaginatedResults<Evaluation> getEvaluationByContentSource(String id, int offset, int limit) throws SynapseException { String url = ENTITY_URI_PATH + "/" + id + EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public PaginatedResults<Evaluation> getEvaluationsPaginated(int offset, int limit) throws SynapseException { String url = EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Evaluation> getAvailableEvaluationsPaginated( int offset, int limit) throws SynapseException { String url = AVAILABLE_EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private String idsToString(List<String> ids) { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String s : ids) { if (firsttime) { firsttime = false; } else { sb.append(","); } sb.append(s); } return sb.toString(); } @Override public PaginatedResults<Evaluation> getAvailableEvaluationsPaginated( int offset, int limit, List<String> evaluationIds) throws SynapseException { String url = AVAILABLE_EVALUATION_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit + "&" + EVALUATION_IDS_FILTER_PARAM + "=" + idsToString(evaluationIds); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Evaluation> results = new PaginatedResults<Evaluation>( Evaluation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Evaluation findEvaluation(String name) throws SynapseException, UnsupportedEncodingException { if (name == null) throw new IllegalArgumentException("Evaluation name cannot be null"); String encodedName = URLEncoder.encode(name, "UTF-8"); String url = EVALUATION_URI_PATH + "/" + NAME + "/" + encodedName; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Evaluation(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public Evaluation updateEvaluation(Evaluation eval) throws SynapseException { if (eval == null) throw new IllegalArgumentException("Evaluation can not be null"); String url = createEntityUri(EVALUATION_URI_PATH, eval.getId()); JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(eval.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Evaluation(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteEvaluation(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String uri = createEntityUri(EVALUATION_URI_PATH, evalId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public Submission createIndividualSubmission(Submission sub, String etag, String challengeEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { if (etag==null) throw new IllegalArgumentException("etag is required."); if (sub.getTeamId()!=null) throw new IllegalArgumentException("For an individual submission Team ID must be null."); if (sub.getContributors()!=null && !sub.getContributors().isEmpty()) throw new IllegalArgumentException("For an individual submission, contributors may not be specified."); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "?" + ETAG + "=" + etag; if (challengeEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "&" + CHALLENGE_ENDPOINT_PARAM + "=" + urlEncode(challengeEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(sub); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Submission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public TeamSubmissionEligibility getTeamSubmissionEligibility(String evaluationId, String teamId) throws SynapseException { if (evaluationId==null) throw new IllegalArgumentException("evaluationId is required."); if (teamId==null) throw new IllegalArgumentException("teamId is required."); String url = EVALUATION_URI_PATH+"/"+evaluationId+TEAM+"/"+teamId+ SUBMISSION_ELIGIBILITY; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new TeamSubmissionEligibility(adapter); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public Submission createTeamSubmission(Submission sub, String etag, String submissionEligibilityHash, String challengeEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { if (etag==null) throw new IllegalArgumentException("etag is required."); if (submissionEligibilityHash==null) throw new IllegalArgumentException("For a Team submission 'submissionEligibilityHash' is required."); if (sub.getTeamId()==null) throw new IllegalArgumentException("For a Team submission Team ID is required."); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "?" + ETAG + "=" + etag + "&" + SUBMISSION_ELIGIBILITY_HASH+"="+submissionEligibilityHash; if (challengeEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "&" + CHALLENGE_ENDPOINT_PARAM + "=" + urlEncode(challengeEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(sub); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, Submission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Add a contributor to an existing submission. This is available to Synapse administrators only. * @param submissionId * @param contributor * @return */ public SubmissionContributor addSubmissionContributor(String submissionId, SubmissionContributor contributor) throws SynapseException { validateStringAsLong(submissionId); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + "/contributor"; try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(contributor); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, SubmissionContributor.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Submission getSubmission(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new Submission(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public SubmissionStatus getSubmissionStatus(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Submission id cannot be null"); String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId + "/" + STATUS; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new SubmissionStatus(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public SubmissionStatus updateSubmissionStatus(SubmissionStatus status) throws SynapseException { if (status == null) { throw new IllegalArgumentException( "SubmissionStatus cannot be null."); } if (status.getAnnotations() != null) { AnnotationsUtils.validateAnnotations(status.getAnnotations()); } String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + status.getId() + STATUS; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(status.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new SubmissionStatus(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } public BatchUploadResponse updateSubmissionStatusBatch(String evaluationId, SubmissionStatusBatch batch) throws SynapseException { if (evaluationId == null) { throw new IllegalArgumentException("evaluationId is required."); } if (batch == null) { throw new IllegalArgumentException( "SubmissionStatusBatch cannot be null."); } if (batch.getIsFirstBatch() == null) { throw new IllegalArgumentException( "isFirstBatch must be set to true or false."); } if (batch.getIsLastBatch() == null) { throw new IllegalArgumentException( "isLastBatch must be set to true or false."); } if (!batch.getIsFirstBatch() && batch.getBatchToken() == null) { throw new IllegalArgumentException( "batchToken cannot be null for any but the first batch."); } List<SubmissionStatus> statuses = batch.getStatuses(); if (statuses == null || statuses.size() == 0) { throw new IllegalArgumentException( "SubmissionStatusBatch must contain at least one SubmissionStatus."); } for (SubmissionStatus status : statuses) { if (status.getAnnotations() != null) { AnnotationsUtils.validateAnnotations(status.getAnnotations()); } } String url = EVALUATION_URI_PATH + "/" + evaluationId + STATUS_BATCH; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(batch.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new BatchUploadResponse(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteSubmission(String subId) throws SynapseException { if (subId == null) throw new IllegalArgumentException("Submission id cannot be null"); String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + subId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @Override public PaginatedResults<Submission> getAllSubmissions(String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionStatus> getAllSubmissionStatuses( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_STATUS_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionStatus> results = new PaginatedResults<SubmissionStatus>( SubmissionStatus.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getAllSubmissionBundles( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE_ALL + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Submission> getAllSubmissionsByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionStatus> getAllSubmissionStatusesByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_STATUS_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionStatus> results = new PaginatedResults<SubmissionStatus>( SubmissionStatus.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getAllSubmissionBundlesByStatus( String evalId, SubmissionStatusEnum status, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE_ALL + STATUS_SUFFIX + status.toString() + "&offset=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Submission> getMySubmissions(String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Submission> results = new PaginatedResults<Submission>( Submission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<SubmissionBundle> getMySubmissionBundles( String evalId, long offset, long limit) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); String url = EVALUATION_URI_PATH + "/" + evalId + "/" + SUBMISSION_BUNDLE + "?offset" + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<SubmissionBundle> results = new PaginatedResults<SubmissionBundle>( SubmissionBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Get a temporary URL to access a File contained in a Submission. * * @param submissionId * @param fileHandleId * @return * @throws ClientProtocolException * @throws MalformedURLException * @throws IOException * @throws SynapseException */ @Override public URL getFileTemporaryUrlForSubmissionFileHandle(String submissionId, String fileHandleId) throws ClientProtocolException, MalformedURLException, IOException, SynapseException { String url = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + FILE + "/" + fileHandleId + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(url); } @Override public void downloadFromSubmission(String submissionId, String fileHandleId, File destinationFile) throws SynapseException { String uri = EVALUATION_URI_PATH + "/" + SUBMISSION + "/" + submissionId + FILE + "/" + fileHandleId; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } @Override public Long getSubmissionCount(String evalId) throws SynapseException { if (evalId == null) throw new IllegalArgumentException("Evaluation id cannot be null"); PaginatedResults<Submission> res = getAllSubmissions(evalId, 0, 0); return res.getTotalNumberOfResults(); } /** * Execute a user query over the Submissions of a specified Evaluation. * * @param query * @return * @throws SynapseException */ @Override public QueryTableResults queryEvaluation(String query) throws SynapseException { try { if (null == query) { throw new IllegalArgumentException("must provide a query"); } String queryUri; queryUri = EVALUATION_QUERY_URI_PATH + URLEncoder.encode(query, "UTF-8"); JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, queryUri, getUserAgent()); JSONObjectAdapter joa = new JSONObjectAdapterImpl(jsonObj); return new QueryTableResults(joa); } catch (Exception e) { throw new SynapseClientException(e); } } /** * Moves an entity and its descendants to the trash can. * * @param entityId * The ID of the entity to be moved to the trash can */ @Override public void moveToTrash(String entityId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_TRASH + "/" + entityId; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Moves an entity and its descendants out of the trash can. The entity will * be restored to the specified parent. If the parent is not specified, it * will be restored to the original parent. */ @Override public void restoreFromTrash(String entityId, String newParentId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_RESTORE + "/" + entityId; if (newParentId != null && !newParentId.isEmpty()) { url = url + "/" + newParentId; } getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Retrieves entities (in the trash can) deleted by the user. */ @Override public PaginatedResults<TrashedEntity> viewTrashForUser(long offset, long limit) throws SynapseException { String url = TRASHCAN_VIEW + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TrashedEntity> results = new PaginatedResults<TrashedEntity>( TrashedEntity.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Purges the specified entity from the trash can. After purging, the entity * will be permanently deleted. */ @Override public void purgeTrashForUser(String entityId) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide an Entity ID."); } String url = TRASHCAN_PURGE + "/" + entityId; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Purges the trash can for the user. All the entities in the trash will be * permanently deleted. */ @Override public void purgeTrashForUser() throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, TRASHCAN_PURGE, null, getUserAgent()); } @Override public void logError(LogEntry logEntry) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(logEntry); jsonObject = createJSONObject(LOG, jsonObject); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override @Deprecated public List<UploadDestination> getUploadDestinations(String parentEntityId) throws SynapseException { // Get the json for this entity as a list wrapper String url = ENTITY + "/" + parentEntityId + "/uploadDestinations"; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { return ListWrapper.unwrap(new JSONObjectAdapterImpl(json), UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T extends StorageLocationSetting> T createStorageLocationSetting(T storageLocation) throws SynapseException { try { JSONObject jsonObject = EntityFactory.createJSONObjectForEntity(storageLocation); jsonObject = getSharedClientConnection().postJson(repoEndpoint, STORAGE_LOCATION, jsonObject.toString(), getUserAgent(), null); return (T) createJsonObjectFromInterface(jsonObject, StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @SuppressWarnings("unchecked") @Override public <T extends StorageLocationSetting> T getMyStorageLocationSetting(Long storageLocationId) throws SynapseException { try { String url = STORAGE_LOCATION + "/" + storageLocationId; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent(), null); return (T) createJsonObjectFromInterface(jsonObject, StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<StorageLocationSetting> getMyStorageLocationSettings() throws SynapseException { try { String url = STORAGE_LOCATION; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, url, getUserAgent(), null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(jsonObject), StorageLocationSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UploadDestinationLocation[] getUploadDestinationLocations(String parentEntityId) throws SynapseException { // Get the json for this entity as a list wrapper String url = ENTITY + "/" + parentEntityId + "/uploadDestinationLocations"; JSONObject json = getSynapseEntity(getFileEndpoint(), url); try { List<UploadDestinationLocation> locations = ListWrapper.unwrap(new JSONObjectAdapterImpl(json), UploadDestinationLocation.class); return locations.toArray(new UploadDestinationLocation[locations.size()]); } catch (JSONObjectAdapterException e) { throw new RuntimeException(e); } } @Override public UploadDestination getUploadDestination(String parentEntityId, Long storageLocationId) throws SynapseException { try { String uri = ENTITY + "/" + parentEntityId + "/uploadDestination/" + storageLocationId; JSONObject jsonObject = getSharedClientConnection().getJson(fileEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UploadDestination getDefaultUploadDestination(String parentEntityId) throws SynapseException { try { String uri = ENTITY + "/" + parentEntityId + "/uploadDestination"; JSONObject jsonObject = getSharedClientConnection().getJson(fileEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, UploadDestination.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ProjectSetting getProjectSetting(String projectId, ProjectSettingsType projectSettingsType) throws SynapseException { try { String uri = PROJECT_SETTINGS + "/" + projectId + "/type/" + projectSettingsType; JSONObject jsonObject = getSharedClientConnection().getJson(repoEndpoint, uri, getUserAgent()); return createJsonObjectFromInterface(jsonObject, ProjectSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ProjectSetting createProjectSetting(ProjectSetting projectSetting) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(projectSetting); jsonObject = getSharedClientConnection().postJson(repoEndpoint, PROJECT_SETTINGS, jsonObject.toString(), getUserAgent(), null); return createJsonObjectFromInterface(jsonObject, ProjectSetting.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateProjectSetting(ProjectSetting projectSetting) throws SynapseException { try { JSONObject jsonObject = EntityFactory .createJSONObjectForEntity(projectSetting); getSharedClientConnection().putJson(repoEndpoint, PROJECT_SETTINGS, jsonObject.toString(), getUserAgent()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteProjectSetting(String projectSettingsId) throws SynapseException { String uri = PROJECT_SETTINGS + "/" + projectSettingsId; getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } @SuppressWarnings("unchecked") private <T extends JSONEntity> T createJsonObjectFromInterface( JSONObject jsonObject, Class<T> expectedType) throws JSONObjectAdapterException { if (jsonObject == null) { return null; } JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObject); String concreteType = adapter.getString("concreteType"); try { JSONEntity obj = (JSONEntity) Class.forName(concreteType).newInstance(); obj.initializeFromJSONObject(adapter); return (T) obj; } catch (Exception e) { throw new RuntimeException(e); } } /** * Add the entity to this user's Favorites list * * @param entityId * @return * @throws SynapseException */ @Override public EntityHeader addFavorite(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String url = createEntityUri(FAVORITE_URI_PATH, entityId); JSONObject jsonObj = getSharedClientConnection().postUri(repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new EntityHeader(adapter); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Remove the entity from this user's Favorites list * * @param entityId * @throws SynapseException */ @Override public void removeFavorite(String entityId) throws SynapseException { if (entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); String uri = createEntityUri(FAVORITE_URI_PATH, entityId); getSharedClientConnection() .deleteUri(repoEndpoint, uri, getUserAgent()); } /** * Retrieve this user's Favorites list * * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<EntityHeader> getFavorites(Integer limit, Integer offset) throws SynapseException { String url = FAVORITE_URI_PATH + "?" + OFFSET + "=" + offset + "&limit=" + limit; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Retrieve this user's Projects list * * @param type the type of list to get * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getMyProjects(ProjectListType type, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(type, null, null, sortColumn, sortDirection, limit, offset); } /** * Retrieve a user's Projects list * * @param userId the user for which to get the project list * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getProjectsFromUser(Long userId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(ProjectListType.OTHER_USER_PROJECTS, userId, null, sortColumn, sortDirection, limit, offset); } /** * Retrieve a teams's Projects list * * @param teamId the team for which to get the project list * @param sortColumn the optional sort column (default by last activity) * @param sortDirection the optional sort direction (default descending) * @param limit * @param offset * @return * @throws SynapseException */ @Override public PaginatedResults<ProjectHeader> getProjectsForTeam(Long teamId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException { return getProjects(ProjectListType.TEAM_PROJECTS, null, teamId, sortColumn, sortDirection, limit, offset); } private PaginatedResults<ProjectHeader> getProjects(ProjectListType type, Long userId, Long teamId, ProjectListSortColumn sortColumn, SortDirection sortDirection, Integer limit, Integer offset) throws SynapseException, SynapseClientException { String url = PROJECTS_URI_PATH + '/' + type.name(); if (userId != null) { url += USER + '/' + userId; } if (teamId != null) { url += TEAM + '/' + teamId; } if (sortColumn == null) { sortColumn = ProjectListSortColumn.LAST_ACTIVITY; } if (sortDirection == null) { sortDirection = SortDirection.DESC; } url += '?' + OFFSET_PARAMETER + offset + '&' + LIMIT_PARAMETER + limit + "&sort=" + sortColumn.name() + "&sortDirection=" + sortDirection.name(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<ProjectHeader> results = new PaginatedResults<ProjectHeader>(ProjectHeader.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Creates a DOI for the specified entity. The DOI will always be associated * with the current version of the entity. */ @Override public void createEntityDoi(String entityId) throws SynapseException { createEntityDoi(entityId, null); } /** * Creates a DOI for the specified entity version. If version is null, the * DOI will always be associated with the current version of the entity. */ @Override public void createEntityDoi(String entityId, Long entityVersion) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide entity ID."); } String url = ENTITY + "/" + entityId; if (entityVersion != null) { url = url + REPO_SUFFIX_VERSION + "/" + entityVersion; } url = url + DOI; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } /** * Gets the DOI for the specified entity version. The DOI is for the current * version of the entity. */ @Override public Doi getEntityDoi(String entityId) throws SynapseException { return getEntityDoi(entityId, null); } /** * Gets the DOI for the specified entity version. If version is null, the * DOI is for the current version of the entity. */ @Override public Doi getEntityDoi(String entityId, Long entityVersion) throws SynapseException { if (entityId == null || entityId.isEmpty()) { throw new IllegalArgumentException("Must provide entity ID."); } try { String url = ENTITY + "/" + entityId; if (entityVersion != null) { url = url + REPO_SUFFIX_VERSION + "/" + entityVersion; } url = url + DOI; JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Doi doi = new Doi(); doi.initializeFromJSONObject(adapter); return doi; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Gets the header information of entities whose file's MD5 matches the * given MD5 checksum. */ @Override public List<EntityHeader> getEntityHeaderByMd5(String md5) throws SynapseException { if (md5 == null || md5.isEmpty()) { throw new IllegalArgumentException( "Must provide a nonempty MD5 string."); } try { String url = ENTITY + "/md5/" + md5; JSONObject jsonObj = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<EntityHeader> results = new PaginatedResults<EntityHeader>( EntityHeader.class); results.initializeFromJSONObject(adapter); return results.getResults(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public String retrieveApiKey() throws SynapseException { try { String url = "/secretKey"; JSONObject jsonObj = getSharedClientConnection().getJson( authEndpoint, url, getUserAgent()); SecretKey key = EntityFactory.createEntityFromJSONObject(jsonObj, SecretKey.class); return key.getSecretKey(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void invalidateApiKey() throws SynapseException { getSharedClientConnection().invalidateApiKey(getUserAgent()); } @Override public AccessControlList updateEvaluationAcl(AccessControlList acl) throws SynapseException { if (acl == null) { throw new IllegalArgumentException("ACL can not be null."); } String url = EVALUATION_ACL_URI_PATH; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(acl.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new AccessControlList(adapter); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getEvaluationAcl(String evalId) throws SynapseException { if (evalId == null) { throw new IllegalArgumentException("Evaluation ID cannot be null."); } String url = EVALUATION_URI_PATH + "/" + evalId + "/acl"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new AccessControlList(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UserEvaluationPermissions getUserEvaluationPermissions(String evalId) throws SynapseException { if (evalId == null) { throw new IllegalArgumentException("Evaluation ID cannot be null."); } String url = EVALUATION_URI_PATH + "/" + evalId + "/permissions"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new UserEvaluationPermissions(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public String appendRowSetToTableStart(AppendableRowSet rowSet, String tableId) throws SynapseException { AppendableRowSetRequest request = new AppendableRowSetRequest(); request.setEntityId(tableId); request.setToAppend(rowSet); return startAsynchJob(AsynchJobType.TableAppendRowSet, request); } @Override public RowReferenceSet appendRowSetToTableGet(String token, String tableId) throws SynapseException, SynapseResultNotReadyException { RowReferenceSetResults rrs = (RowReferenceSetResults) getAsyncResult( AsynchJobType.TableAppendRowSet, token, tableId); return rrs.getRowReferenceSet(); } @Override public String startTableTransactionJob(List<TableUpdateRequest> changes, String tableId) throws SynapseException { TableUpdateTransactionRequest request = new TableUpdateTransactionRequest(); request.setEntityId(tableId); request.setChanges(changes); return startAsynchJob(AsynchJobType.TableTransaction, request); } @Override public List<TableUpdateResponse> getTableTransactionJobResults(String token, String tableId) throws SynapseException, SynapseResultNotReadyException { TableUpdateTransactionResponse response = (TableUpdateTransactionResponse) getAsyncResult( AsynchJobType.TableTransaction, token, tableId); return response.getResults(); } @Override public RowReferenceSet appendRowsToTable(AppendableRowSet rowSet, long timeout, String tableId) throws SynapseException, InterruptedException { long start = System.currentTimeMillis(); // Start the job String jobId = appendRowSetToTableStart(rowSet, tableId); do { try { return appendRowSetToTableGet(jobId, tableId); } catch (SynapseResultNotReadyException e) { Thread.sleep(1000); } } while (System.currentTimeMillis() - start < timeout); // ran out of time. throw new SynapseClientException("Timed out waiting for jobId: " + jobId); } @Override public RowReferenceSet deleteRowsFromTable(RowSelection toDelete) throws SynapseException { if (toDelete == null) throw new IllegalArgumentException("RowSelection cannot be null"); if (toDelete.getTableId() == null) throw new IllegalArgumentException( "RowSelection.tableId cannot be null"); String uri = ENTITY + "/" + toDelete.getTableId() + TABLE + "/deleteRows"; try { String jsonBody = EntityFactory.createJSONStringForEntity(toDelete); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, RowReferenceSet.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public RowSet getRowsFromTable(RowReferenceSet toGet) throws SynapseException, SynapseTableUnavailableException { if (toGet == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); if (toGet.getTableId() == null) throw new IllegalArgumentException( "RowReferenceSet.tableId cannot be null"); String uri = ENTITY + "/" + toGet.getTableId() + TABLE + "/getRows"; try { String jsonBody = EntityFactory.createJSONStringForEntity(toGet); JSONObject obj = getSharedClientConnection().postJson(repoEndpoint, uri, jsonBody, getUserAgent(), null); return EntityFactory.createEntityFromJSONObject(obj, RowSet.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public TableFileHandleResults getFileHandlesFromTable( RowReferenceSet fileHandlesToFind) throws SynapseException { if (fileHandlesToFind == null) throw new IllegalArgumentException("RowReferenceSet cannot be null"); String uri = ENTITY + "/" + fileHandlesToFind.getTableId() + TABLE + FILE_HANDLES; return asymmetricalPost(getRepoEndpoint(), uri, fileHandlesToFind, TableFileHandleResults.class, null); } /** * Get the temporary URL for the data file of a file handle column for a * row. This is an alternative to downloading the file. * * @param entityId * @return * @throws IOException * @throws SynapseException */ @Override public URL getTableFileHandleTemporaryUrl(String tableId, RowReference row, String columnId) throws IOException, SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromTableFileHandleTemporaryUrl(String tableId, RowReference row, String columnId, File destinationFile) throws SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } @Override public URL getTableFileHandlePreviewTemporaryUrl(String tableId, RowReference row, String columnId) throws IOException, SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE_PREVIEW + QUERY_REDIRECT_PARAMETER + "false"; return getUrl(uri); } @Override public void downloadFromTableFileHandlePreviewTemporaryUrl(String tableId, RowReference row, String columnId, File destinationFile) throws SynapseException { String uri = getUriForFileHandle(tableId, row, columnId) + FILE_PREVIEW; getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, destinationFile, getUserAgent()); } private static String getUriForFileHandle(String tableId, RowReference row, String columnId) { return ENTITY + "/" + tableId + TABLE + COLUMN + "/" + columnId + ROW_ID + "/" + row.getRowId() + ROW_VERSION + "/" + row.getVersionNumber(); } @Override public String queryTableEntityBundleAsyncStart(String sql, Long offset, Long limit, boolean isConsistent, int partsMask, String tableId) throws SynapseException { Query query = new Query(); query.setSql(sql); query.setIsConsistent(isConsistent); query.setOffset(offset); query.setLimit(limit); QueryBundleRequest bundleRequest = new QueryBundleRequest(); bundleRequest.setEntityId(tableId); bundleRequest.setQuery(query); bundleRequest.setPartMask((long) partsMask); return startAsynchJob(AsynchJobType.TableQuery, bundleRequest); } @Override public QueryResultBundle queryTableEntityBundleAsyncGet( String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (QueryResultBundle) getAsyncResult(AsynchJobType.TableQuery, asyncJobToken, tableId); } @Override public String queryTableEntityNextPageAsyncStart(String nextPageToken, String tableId) throws SynapseException { QueryNextPageToken queryNextPageToken = new QueryNextPageToken(); queryNextPageToken.setEntityId(tableId); queryNextPageToken.setToken(nextPageToken); return startAsynchJob(AsynchJobType.TableQueryNextPage, queryNextPageToken); } @Override public QueryResult queryTableEntityNextPageAsyncGet(String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (QueryResult) getAsyncResult(AsynchJobType.TableQueryNextPage, asyncJobToken, tableId); } @Override public String downloadCsvFromTableAsyncStart(String sql, boolean writeHeader, boolean includeRowIdAndRowVersion, CsvTableDescriptor csvDescriptor, String tableId) throws SynapseException { DownloadFromTableRequest downloadRequest = new DownloadFromTableRequest(); downloadRequest.setEntityId(tableId); downloadRequest.setSql(sql); downloadRequest.setWriteHeader(writeHeader); downloadRequest.setIncludeRowIdAndRowVersion(includeRowIdAndRowVersion); downloadRequest.setCsvTableDescriptor(csvDescriptor); return startAsynchJob(AsynchJobType.TableCSVDownload, downloadRequest); } @Override public DownloadFromTableResult downloadCsvFromTableAsyncGet( String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (DownloadFromTableResult) getAsyncResult( AsynchJobType.TableCSVDownload, asyncJobToken, tableId); } @Override public String uploadCsvToTableAsyncStart(String tableId, String fileHandleId, String etag, Long linesToSkip, CsvTableDescriptor csvDescriptor) throws SynapseException { return uploadCsvToTableAsyncStart(tableId, fileHandleId, etag, linesToSkip, csvDescriptor, null); } @Override public String uploadCsvToTableAsyncStart(String tableId, String fileHandleId, String etag, Long linesToSkip, CsvTableDescriptor csvDescriptor, List<String> columnIds) throws SynapseException { UploadToTableRequest uploadRequest = new UploadToTableRequest(); uploadRequest.setTableId(tableId); uploadRequest.setUploadFileHandleId(fileHandleId); uploadRequest.setUpdateEtag(etag); uploadRequest.setLinesToSkip(linesToSkip); uploadRequest.setCsvTableDescriptor(csvDescriptor); uploadRequest.setColumnIds(columnIds); return startAsynchJob(AsynchJobType.TableCSVUpload, uploadRequest); } @Override public UploadToTableResult uploadCsvToTableAsyncGet(String asyncJobToken, String tableId) throws SynapseException, SynapseResultNotReadyException { return (UploadToTableResult) getAsyncResult( AsynchJobType.TableCSVUpload, asyncJobToken, tableId); } @Override public String uploadCsvTablePreviewAsyncStart(UploadToTablePreviewRequest request) throws SynapseException { return startAsynchJob(AsynchJobType.TableCSVUploadPreview, request); } @Override public UploadToTablePreviewResult uploadCsvToTablePreviewAsyncGet(String asyncJobToken) throws SynapseException, SynapseResultNotReadyException { String entityId = null; return (UploadToTablePreviewResult) getAsyncResult( AsynchJobType.TableCSVUploadPreview, asyncJobToken, entityId); } @Override public ColumnModel createColumnModel(ColumnModel model) throws SynapseException { if (model == null) throw new IllegalArgumentException("ColumnModel cannot be null"); String url = COLUMN; return createJSONEntity(url, model); } @Override public List<ColumnModel> createColumnModels(List<ColumnModel> models) throws SynapseException { if (models == null) { throw new IllegalArgumentException("ColumnModel cannot be null"); } String url = COLUMN_BATCH; List<ColumnModel> results = createJSONEntityFromListWrapper(url, ListWrapper.wrap(models, ColumnModel.class), ColumnModel.class); return results; } @Override public ColumnModel getColumnModel(String columnId) throws SynapseException { if (columnId == null) throw new IllegalArgumentException("ColumnId cannot be null"); String url = COLUMN + "/" + columnId; try { return getJSONEntity(url, ColumnModel.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<ColumnModel> getColumnModelsForTableEntity(String tableEntityId) throws SynapseException { if (tableEntityId == null) throw new IllegalArgumentException("tableEntityId cannot be null"); String url = ENTITY + "/" + tableEntityId + COLUMN; try { PaginatedColumnModels pcm = getJSONEntity(url, PaginatedColumnModels.class); return pcm.getResults(); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<ColumnModel> getDefaultColumnsForView(ViewType viewType) throws SynapseException { if(viewType == null){ throw new IllegalArgumentException("Viewtype cannot be null"); } try { String url = COLUMN_VIEW_DEFAULT+viewType.name(); JSONObject jsonObject = getSharedClientConnection().getJson( repoEndpoint, url, getUserAgent()); return ListWrapper.unwrap(new JSONObjectAdapterImpl(jsonObject), ColumnModel.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedColumnModels listColumnModels(String prefix, Long limit, Long offset) throws SynapseException { String url = buildListColumnModelUrl(prefix, limit, offset); try { return getJSONEntity(url, PaginatedColumnModels.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Build up the URL for listing all ColumnModels * * @param prefix * @param limit * @param offset * @return */ static String buildListColumnModelUrl(String prefix, Long limit, Long offset) { StringBuilder builder = new StringBuilder(); builder.append(COLUMN); int count = 0; if (prefix != null || limit != null || offset != null) { builder.append("?"); } if (prefix != null) { builder.append("prefix="); builder.append(prefix); count++; } if (limit != null) { if (count > 0) { builder.append("&"); } builder.append("limit="); builder.append(limit); count++; } if (offset != null) { if (count > 0) { builder.append("&"); } builder.append("offset="); builder.append(offset); } return builder.toString(); } /** * Start a new Asynchronous Job * * @param jobBody * @return * @throws SynapseException */ @Override public AsynchronousJobStatus startAsynchronousJob( AsynchronousRequestBody jobBody) throws SynapseException { if (jobBody == null) throw new IllegalArgumentException("JobBody cannot be null"); String url = ASYNCHRONOUS_JOB; return asymmetricalPost(getRepoEndpoint(), url, jobBody, AsynchronousJobStatus.class, null); } /** * Get the status of an Asynchronous Job from its ID. * * @param jobId * @return * @throws SynapseException * @throws JSONObjectAdapterException */ @Override public AsynchronousJobStatus getAsynchronousJobStatus(String jobId) throws JSONObjectAdapterException, SynapseException { if (jobId == null) throw new IllegalArgumentException("JobId cannot be null"); String url = ASYNCHRONOUS_JOB + "/" + jobId; return getJSONEntity(url, AsynchronousJobStatus.class); } @Override public Team createTeam(Team team) throws SynapseException { try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(team); jsonObj = createJSONObject(TEAM, jsonObj); return initializeFromJSONObject(jsonObj, Team.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Team getTeam(String id) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + id); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Team results = new Team(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Team> getTeams(String fragment, long limit, long offset) throws SynapseException { String uri = null; if (fragment == null) { uri = TEAMS + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAMS + "?" + NAME_FRAGMENT_FILTER + "=" + urlEncode(fragment) + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Team> results = new PaginatedResults<Team>(Team.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<Team> listTeams(List<Long> ids) throws SynapseException { try { IdList idList = new IdList(); idList.setList(ids); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), TEAM_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), Team.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<Team> getTeamsForUser(String memberId, long limit, long offset) throws SynapseException { String uri = USER + "/" + memberId + TEAM + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<Team> results = new PaginatedResults<Team>(Team.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static String createGetTeamIconURI(String teamId, boolean redirect) { return TEAM + "/" + teamId + ICON + "?" + REDIRECT_PARAMETER + redirect; } @Override public URL getTeamIcon(String teamId) throws SynapseException { try { return getUrl(createGetTeamIconURI(teamId, false)); } catch (IOException e) { throw new SynapseClientException(e); } } // alternative to getTeamIcon @Override public void downloadTeamIcon(String teamId, File target) throws SynapseException { String uri = createGetTeamIconURI(teamId, true); getSharedClientConnection().downloadFromSynapse( getRepoEndpoint() + uri, null, target, getUserAgent()); } @Override public Team updateTeam(Team team) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(team.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, TEAM, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Team(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteTeam(String teamId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, TEAM + "/" + teamId, getUserAgent()); } @Override public void addTeamMember(String teamId, String memberId, String teamEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = TEAM + "/" + teamId + MEMBER + "/" + memberId; if (teamEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + TEAM_ENDPOINT_PARAM + "=" + urlEncode(teamEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } getSharedClientConnection().putJson(repoEndpoint, uri, new JSONObject().toString(), getUserAgent()); } @Override public ResponseMessage addTeamMember(JoinTeamSignedToken joinTeamSignedToken, String teamEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = TEAM + "Member"; if (teamEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + TEAM_ENDPOINT_PARAM + "=" + urlEncode(teamEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } return asymmetricalPut(getRepoEndpoint(), uri, joinTeamSignedToken, ResponseMessage.class); } private static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public PaginatedResults<TeamMember> getTeamMembers(String teamId, String fragment, long limit, long offset) throws SynapseException { String uri = null; if (fragment == null) { uri = TEAM_MEMBERS + "/" + teamId + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM_MEMBERS + "/" + teamId + "?" + NAME_FRAGMENT_FILTER + "=" + urlEncode(fragment) + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<TeamMember> results = new PaginatedResults<TeamMember>( TeamMember.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<TeamMember> listTeamMembers(String teamId, List<Long> ids) throws SynapseException { try { IdList idList = new IdList(); idList.setList(ids); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), TEAM+"/"+teamId+MEMBER_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), TeamMember.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public List<TeamMember> listTeamMembers(List<Long> teamIds, String userId) throws SynapseException { try { IdList idList = new IdList(); idList.setList(teamIds); String jsonString = EntityFactory.createJSONStringForEntity(idList); JSONObject responseBody = getSharedClientConnection().postJson( getRepoEndpoint(), USER+"/"+userId+MEMBER_LIST, jsonString, getUserAgent(), null, null); return ListWrapper.unwrap(new JSONObjectAdapterImpl(responseBody), TeamMember.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } public TeamMember getTeamMember(String teamId, String memberId) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + teamId + MEMBER + "/" + memberId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); TeamMember result = new TeamMember(); try { result.initializeFromJSONObject(adapter); return result; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void removeTeamMember(String teamId, String memberId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, TEAM + "/" + teamId + MEMBER + "/" + memberId, getUserAgent()); } @Override public void setTeamMemberPermissions(String teamId, String memberId, boolean isAdmin) throws SynapseException { getSharedClientConnection().putJson(repoEndpoint, TEAM + "/" + teamId + MEMBER + "/" + memberId + PERMISSION + "?" + TEAM_MEMBERSHIP_PERMISSION + "=" + isAdmin, "", getUserAgent()); } @Override public TeamMembershipStatus getTeamMembershipStatus(String teamId, String principalId) throws SynapseException { JSONObject jsonObj = getEntity(TEAM + "/" + teamId + MEMBER + "/" + principalId + MEMBERSHIP_STATUS); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); TeamMembershipStatus results = new TeamMembershipStatus(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList getTeamACL(String teamId) throws SynapseException { if (teamId == null) { throw new IllegalArgumentException("Team ID cannot be null."); } String url = TEAM + "/" + teamId + "/acl"; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); try { return new AccessControlList(adapter); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public AccessControlList updateTeamACL(AccessControlList acl) throws SynapseException { if (acl == null) { throw new IllegalArgumentException("ACL can not be null."); } String url = TEAM+"/acl"; JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; try { obj = new JSONObject(acl.writeToJSONObject(toUpdateAdapter) .toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson( repoEndpoint, url, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new AccessControlList(adapter); } catch (JSONException e) { throw new SynapseClientException(e); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipInvtnSubmission createMembershipInvitation( MembershipInvtnSubmission invitation, String acceptInvitationEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { try { JSONObject jsonObj = EntityFactory .createJSONObjectForEntity(invitation); String uri = MEMBERSHIP_INVITATION; if (acceptInvitationEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + ACCEPT_INVITATION_ENDPOINT_PARAM + "=" + urlEncode(acceptInvitationEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, MembershipInvtnSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipInvtnSubmission getMembershipInvitation(String invitationId) throws SynapseException { JSONObject jsonObj = getEntity(MEMBERSHIP_INVITATION + "/" + invitationId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MembershipInvtnSubmission results = new MembershipInvtnSubmission(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipInvitation> getOpenMembershipInvitations( String memberId, String teamId, long limit, long offset) throws SynapseException { String uri = null; if (teamId == null) { uri = USER + "/" + memberId + OPEN_MEMBERSHIP_INVITATION + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = USER + "/" + memberId + OPEN_MEMBERSHIP_INVITATION + "?" + TEAM_ID_REQUEST_PARAMETER + "=" + teamId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipInvitation> results = new PaginatedResults<MembershipInvitation>( MembershipInvitation.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipInvtnSubmission> getOpenMembershipInvitationSubmissions( String teamId, String inviteeId, long limit, long offset) throws SynapseException { String uri = null; if (inviteeId == null) { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_INVITATION + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_INVITATION + "?" + INVITEE_ID_REQUEST_PARAMETER + "=" + inviteeId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipInvtnSubmission> results = new PaginatedResults<MembershipInvtnSubmission>( MembershipInvtnSubmission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMembershipInvitation(String invitationId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, MEMBERSHIP_INVITATION + "/" + invitationId, getUserAgent()); } @Override public MembershipRqstSubmission createMembershipRequest( MembershipRqstSubmission request, String acceptRequestEndpoint, String notificationUnsubscribeEndpoint) throws SynapseException { try { String uri = MEMBERSHIP_REQUEST; if (acceptRequestEndpoint!=null && notificationUnsubscribeEndpoint!=null) { uri += "?" + ACCEPT_REQUEST_ENDPOINT_PARAM + "=" + urlEncode(acceptRequestEndpoint) + "&" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(request); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, MembershipRqstSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public MembershipRqstSubmission getMembershipRequest(String requestId) throws SynapseException { JSONObject jsonObj = getEntity(MEMBERSHIP_REQUEST + "/" + requestId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); MembershipRqstSubmission results = new MembershipRqstSubmission(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipRequest> getOpenMembershipRequests( String teamId, String requestorId, long limit, long offset) throws SynapseException { String uri = null; if (requestorId == null) { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_REQUEST + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = TEAM + "/" + teamId + OPEN_MEMBERSHIP_REQUEST + "?" + REQUESTOR_ID_REQUEST_PARAMETER + "=" + requestorId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipRequest> results = new PaginatedResults<MembershipRequest>( MembershipRequest.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<MembershipRqstSubmission> getOpenMembershipRequestSubmissions( String requesterId, String teamId, long limit, long offset) throws SynapseException { String uri = null; if (teamId == null) { uri = USER + "/" + requesterId + OPEN_MEMBERSHIP_REQUEST + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = USER + "/" + requesterId + OPEN_MEMBERSHIP_REQUEST + "?" + TEAM_ID_REQUEST_PARAMETER + "=" + teamId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<MembershipRqstSubmission> results = new PaginatedResults<MembershipRqstSubmission>( MembershipRqstSubmission.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteMembershipRequest(String requestId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, MEMBERSHIP_REQUEST + "/" + requestId, getUserAgent()); } @Override public void createUser(NewUser user) throws SynapseException { try { JSONObject obj = EntityFactory.createJSONObjectForEntity(user); getSharedClientConnection().postJson(authEndpoint, "/user", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void sendPasswordResetEmail(String email) throws SynapseException { try { Username user = new Username(); user.setEmail(email); JSONObject obj = EntityFactory.createJSONObjectForEntity(user); getSharedClientConnection().postJson(authEndpoint, "/user/password/email", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void changePassword(String sessionToken, String newPassword) throws SynapseException { try { ChangePasswordRequest change = new ChangePasswordRequest(); change.setSessionToken(sessionToken); change.setPassword(newPassword); JSONObject obj = EntityFactory.createJSONObjectForEntity(change); getSharedClientConnection().postJson(authEndpoint, "/user/password", obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void signTermsOfUse(String sessionToken, boolean acceptTerms) throws SynapseException { signTermsOfUse(sessionToken, DomainType.SYNAPSE, acceptTerms); } @Override public void signTermsOfUse(String sessionToken, DomainType domain, boolean acceptTerms) throws SynapseException { try { Session session = new Session(); session.setSessionToken(sessionToken); session.setAcceptsTermsOfUse(acceptTerms); Map<String, String> parameters = domainToParameterMap(domain); JSONObject obj = EntityFactory.createJSONObjectForEntity(session); getSharedClientConnection().postJson(authEndpoint, "/termsOfUse", obj.toString(), getUserAgent(), parameters); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString) throws SynapseException { return passThroughOpenIDParameters(queryString, false); } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString, Boolean createUserIfNecessary) throws SynapseException { return passThroughOpenIDParameters(queryString, createUserIfNecessary, DomainType.SYNAPSE); } @Deprecated @Override public Session passThroughOpenIDParameters(String queryString, Boolean createUserIfNecessary, DomainType domain) throws SynapseException { try { URIBuilder builder = new URIBuilder(); builder.setPath("/openIdCallback"); builder.setQuery(queryString); builder.setParameter("org.sagebionetworks.createUserIfNecessary", createUserIfNecessary.toString()); Map<String, String> parameters = domainToParameterMap(domain); JSONObject session = getSharedClientConnection().postJson( authEndpoint, builder.toString(), "", getUserAgent(), parameters); return EntityFactory.createEntityFromJSONObject(session, Session.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#getOAuth2AuthenticationUrl(org.sagebionetworks.repo.model.oauth.OAuthUrlRequest) */ @Override public OAuthUrlResponse getOAuth2AuthenticationUrl(OAuthUrlRequest request) throws SynapseException{ return asymmetricalPost(getAuthEndpoint(), AUTH_OAUTH_2_AUTH_URL, request, OAuthUrlResponse.class, null); } /* * (non-Javadoc) * @see org.sagebionetworks.client.SynapseClient#validateOAuthAuthenticationCode(org.sagebionetworks.repo.model.oauth.OAuthValidationRequest) */ @Override public Session validateOAuthAuthenticationCode(OAuthValidationRequest request) throws SynapseException{ return asymmetricalPost(getAuthEndpoint(), AUTH_OAUTH_2_SESSION, request, Session.class, null); } @Override public PrincipalAlias bindOAuthProvidersUserId(OAuthValidationRequest request) throws SynapseException { return asymmetricalPost(authEndpoint, AUTH_OAUTH_2_ALIAS, request, PrincipalAlias.class, null); } @Override public void unbindOAuthProvidersUserId(OAuthProvider provider, String alias) throws SynapseException { if (provider==null) throw new IllegalArgumentException("provider is required."); if (alias==null) throw new IllegalArgumentException("alias is required."); try { getSharedClientConnection().deleteUri(authEndpoint, AUTH_OAUTH_2_ALIAS+"?provider="+ URLEncoder.encode(provider.name(), "UTF-8")+ "&"+"alias="+URLEncoder.encode(alias, "UTF-8"), getUserAgent()); } catch (UnsupportedEncodingException e) { throw new SynapseClientException(e); } } private Map<String, String> domainToParameterMap(DomainType domain) { Map<String, String> parameters = Maps.newHashMap(); parameters.put(AuthorizationConstants.DOMAIN_PARAM, domain.name()); return parameters; } @Override public Quiz getCertifiedUserTest() throws SynapseException { JSONObject jsonObj = getEntity(CERTIFIED_USER_TEST); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Quiz results = new Quiz(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PassingRecord submitCertifiedUserTestResponse(QuizResponse response) throws SynapseException { try { JSONObject jsonObj = EntityFactory .createJSONObjectForEntity(response); jsonObj = createJSONObject(CERTIFIED_USER_TEST_RESPONSE, jsonObj); return initializeFromJSONObject(jsonObj, PassingRecord.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void setCertifiedUserStatus(String principalId, boolean status) throws SynapseException { String url = USER + "/" + principalId + CERTIFIED_USER_STATUS + "?isCertified=" + status; getSharedClientConnection().putJson(repoEndpoint, url, null, getUserAgent()); } @Override public PaginatedResults<QuizResponse> getCertifiedUserTestResponses( long offset, long limit, String principalId) throws SynapseException { String uri = null; if (principalId == null) { uri = CERTIFIED_USER_TEST_RESPONSE + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } else { uri = CERTIFIED_USER_TEST_RESPONSE + "?" + PRINCIPAL_ID_REQUEST_PARAM + "=" + principalId + "&" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<QuizResponse> results = new PaginatedResults<QuizResponse>( QuizResponse.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteCertifiedUserTestResponse(String id) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, CERTIFIED_USER_TEST_RESPONSE + "/" + id, getUserAgent()); } @Override public PassingRecord getCertifiedUserPassingRecord(String principalId) throws SynapseException { if (principalId == null) throw new IllegalArgumentException("principalId may not be null."); JSONObject jsonObj = getEntity(USER + "/" + principalId + CERTIFIED_USER_PASSING_RECORD); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PassingRecord results = new PassingRecord(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<PassingRecord> getCertifiedUserPassingRecords( long offset, long limit, String principalId) throws SynapseException { if (principalId == null) throw new IllegalArgumentException("principalId may not be null."); String uri = USER + "/" + principalId + CERTIFIED_USER_PASSING_RECORDS + "?" + OFFSET + "=" + offset + "&" + LIMIT + "=" + limit; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<PassingRecord> results = new PaginatedResults<PassingRecord>( PassingRecord.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityQueryResults entityQuery(EntityQuery query) throws SynapseException { return asymmetricalPost(getRepoEndpoint(), QUERY, query, EntityQueryResults.class, null); } @Override public Challenge createChallenge(Challenge challenge) throws SynapseException { try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(challenge); jsonObj = createJSONObject(CHALLENGE, jsonObj); return initializeFromJSONObject(jsonObj, Challenge.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } /** * Returns the Challenge given its ID. Caller must * have READ permission on the associated Project. * * @param challengeId * @return * @throws SynapseException */ @Override public Challenge getChallenge(String challengeId) throws SynapseException { validateStringAsLong(challengeId); JSONObject jsonObj = getEntity(CHALLENGE+"/"+challengeId); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Challenge results = new Challenge(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Challenge getChallengeForProject(String projectId) throws SynapseException { if (projectId==null) throw new IllegalArgumentException("projectId may not be null."); JSONObject jsonObj = getEntity(ENTITY+"/"+projectId+CHALLENGE); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); Challenge results = new Challenge(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static final void validateStringAsLong(String s) throws SynapseClientException { if (s==null) throw new NullPointerException(); try { Long.parseLong(s); } catch (NumberFormatException e) { throw new SynapseClientException("Expected integer but found "+s, e); } } @Override public PaginatedIds listChallengeParticipants(String challengeId, Boolean affiliated, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+"/participant"; boolean anyParameters = false; if (affiliated!=null) { uri += "?affiliated="+affiliated; anyParameters = true; } if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengePagedResults listChallengesForParticipant(String participantPrincipalId, Long limit, Long offset) throws SynapseException { validateStringAsLong(participantPrincipalId); String uri = CHALLENGE+"?participantId="+participantPrincipalId; if (limit!=null) uri+= "&"+LIMIT+"="+limit; if (offset!=null) uri+="&"+OFFSET+"="+offset; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); ChallengePagedResults results = new ChallengePagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Challenge updateChallenge(Challenge challenge) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; String uri = CHALLENGE+"/"+challenge.getId(); try { obj = new JSONObject(challenge.writeToJSONObject(toUpdateAdapter).toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new Challenge(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } @Override public void deleteChallenge(String id) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, CHALLENGE + "/" + id, getUserAgent()); } /** * Register a Team for a Challenge. The user making this request must be * registered for the Challenge and be an administrator of the Team. * * @param challengeId * @param teamId * @throws SynapseException */ @Override public ChallengeTeam createChallengeTeam(ChallengeTeam challengeTeam) throws SynapseException { try { if (challengeTeam.getChallengeId()==null) throw new IllegalArgumentException("challenge ID is required."); JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(challengeTeam); jsonObj = createJSONObject(CHALLENGE+"/"+challengeTeam.getChallengeId()+CHALLENGE_TEAM, jsonObj); return initializeFromJSONObject(jsonObj, ChallengeTeam.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengeTeamPagedResults listChallengeTeams(String challengeId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+CHALLENGE_TEAM; boolean anyParameters = false; if (limit!=null) { uri+= (anyParameters?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); ChallengeTeamPagedResults results = new ChallengeTeamPagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedIds listRegistratableTeams(String challengeId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); String uri = CHALLENGE+"/"+challengeId+REGISTRATABLE_TEAM; boolean anyParameters = false; if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedIds listSubmissionTeams(String challengeId, String submitterPrincipalId, Long limit, Long offset) throws SynapseException { validateStringAsLong(challengeId); validateStringAsLong(submitterPrincipalId); String uri = CHALLENGE+"/"+challengeId+SUBMISSION_TEAMS+"?submitterPrincipalId="+submitterPrincipalId; if (limit!=null) uri+= "&"+LIMIT+"="+limit; if (offset!=null) uri+="&"+OFFSET+"="+offset; JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedIds results = new PaginatedIds(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ChallengeTeam updateChallengeTeam(ChallengeTeam challengeTeam) throws SynapseException { JSONObjectAdapter toUpdateAdapter = new JSONObjectAdapterImpl(); JSONObject obj; String challengeId = challengeTeam.getChallengeId(); if (challengeId==null) throw new IllegalArgumentException("challenge ID is required."); String challengeTeamId = challengeTeam.getId(); if (challengeTeamId==null) throw new IllegalArgumentException("ChallengeTeam ID is required."); String uri = CHALLENGE+"/"+challengeId+CHALLENGE_TEAM+"/"+challengeTeamId; try { obj = new JSONObject(challengeTeam.writeToJSONObject(toUpdateAdapter).toJSONString()); JSONObject jsonObj = getSharedClientConnection().putJson(repoEndpoint, uri, obj.toString(), getUserAgent()); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); return new ChallengeTeam(adapter); } catch (JSONException e1) { throw new RuntimeException(e1); } catch (JSONObjectAdapterException e1) { throw new RuntimeException(e1); } } /** * Remove a registered Team from a Challenge. * The user making this request must be registered for the Challenge and * be an administrator of the Team. * * @param challengeTeamId * @throws SynapseException */ @Override public void deleteChallengeTeam(String challengeTeamId) throws SynapseException { validateStringAsLong(challengeTeamId); getSharedClientConnection().deleteUri(repoEndpoint, CHALLENGE_TEAM + "/" + challengeTeamId, getUserAgent()); } public void addTeamToChallenge(String challengeId, String teamId) throws SynapseException { throw new RuntimeException("Not Yet Implemented"); } /** * Remove a registered Team from a Challenge. The user making this request * must be registered for the Challenge and be an administrator of the Team. * * @param challengeId * @param teamId * @throws SynapseException */ public void removeTeamFromChallenge(String challengeId, String teamId) throws SynapseException { throw new RuntimeException("Not Yet Implemented"); } @Override public VerificationSubmission createVerificationSubmission( VerificationSubmission verificationSubmission, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = VERIFICATION_SUBMISSION; if (notificationUnsubscribeEndpoint!=null) { uri += "?" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(verificationSubmission); jsonObj = createJSONObject(uri, jsonObj); return initializeFromJSONObject(jsonObj, VerificationSubmission.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public VerificationPagedResults listVerificationSubmissions( VerificationStateEnum currentState, Long submitterId, Long limit, Long offset) throws SynapseException { String uri = VERIFICATION_SUBMISSION; boolean anyParameters = false; if (currentState!=null) { uri+=(anyParameters ?"&":"?")+CURRENT_VERIFICATION_STATE+"="+currentState; anyParameters = true; } if (submitterId!=null) { uri+=(anyParameters ?"&":"?")+VERIFIED_USER_ID+"="+submitterId; anyParameters = true; } if (limit!=null) { uri+=(anyParameters ?"&":"?")+LIMIT+"="+limit; anyParameters = true; } if (offset!=null) { uri+=(anyParameters ?"&":"?")+OFFSET+"="+offset; anyParameters = true; } JSONObject jsonObj = getEntity(uri); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); VerificationPagedResults results = new VerificationPagedResults(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void updateVerificationState(long verificationId, VerificationState verificationState, String notificationUnsubscribeEndpoint) throws SynapseException { String uri = VERIFICATION_SUBMISSION+"/"+verificationId+VERIFICATION_STATE; if (notificationUnsubscribeEndpoint!=null) { uri += "?" + NOTIFICATION_UNSUBSCRIBE_ENDPOINT_PARAM + "=" + urlEncode(notificationUnsubscribeEndpoint); } try { JSONObject jsonObj = EntityFactory.createJSONObjectForEntity(verificationState); createJSONObject(uri, jsonObj); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void deleteVerificationSubmission(long verificationId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, VERIFICATION_SUBMISSION+"/"+verificationId, getUserAgent()); } @Override public UserBundle getMyOwnUserBundle(int mask) throws SynapseException { JSONObject jsonObj = getEntity(USER+USER_BUNDLE+"?mask="+mask); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserBundle results = new UserBundle(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public UserBundle getUserBundle(long principalId, int mask) throws SynapseException { JSONObject jsonObj = getEntity(USER+"/"+principalId+USER_BUNDLE+"?mask="+mask); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); UserBundle results = new UserBundle(); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } private static String createFileDownloadUri(FileHandleAssociation fileHandleAssociation, boolean redirect) { return FILE + "/" + fileHandleAssociation.getFileHandleId() + "?" + FILE_ASSOCIATE_TYPE + "=" + fileHandleAssociation.getAssociateObjectType() + "&" + FILE_ASSOCIATE_ID + "=" + fileHandleAssociation.getAssociateObjectId() + "&" + REDIRECT_PARAMETER + redirect; } @Override public URL getFileURL(FileHandleAssociation fileHandleAssociation) throws SynapseException { try { return getUrl(getFileEndpoint(), createFileDownloadUri(fileHandleAssociation, false)); } catch (IOException e) { throw new SynapseClientException(e); } } @Override public void downloadFile(FileHandleAssociation fileHandleAssociation, File target) throws SynapseException { String uri = createFileDownloadUri(fileHandleAssociation, true); getSharedClientConnection().downloadFromSynapse( getFileEndpoint() + uri, null, target, getUserAgent()); } @Override public Forum getForumByProjectId(String projectId) throws SynapseException { try { ValidateArgument.required(projectId, "projectId"); return getJSONEntity(PROJECT+"/"+projectId+FORUM, Forum.class); } catch (Exception e) { throw new SynapseClientException(e); } } @Override public Forum getForum(String forumId) throws SynapseException { try { ValidateArgument.required(forumId, "forumId"); return getJSONEntity(FORUM+"/"+forumId, Forum.class); } catch (Exception e) { throw new SynapseClientException(e); } } @Override public DiscussionThreadBundle createThread(CreateDiscussionThread toCreate) throws SynapseException { ValidateArgument.required(toCreate, "toCreate"); return asymmetricalPost(repoEndpoint, THREAD, toCreate, DiscussionThreadBundle.class, null); } @Override public DiscussionThreadBundle getThread(String threadId) throws SynapseException { try { ValidateArgument.required(threadId, "threadId"); String url = THREAD+"/"+threadId; return getJSONEntity(url, DiscussionThreadBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionThreadBundle> getThreadsForForum( String forumId, Long limit, Long offset, DiscussionThreadOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = FORUM+"/"+forumId+THREADS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter.toString(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionThreadBundle> results = new PaginatedResults<DiscussionThreadBundle>(DiscussionThreadBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public DiscussionThreadBundle updateThreadTitle(String threadId, UpdateThreadTitle newTitle) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(newTitle, "newTitle"); return asymmetricalPut(repoEndpoint, THREAD+"/"+threadId+THREAD_TITLE, newTitle, DiscussionThreadBundle.class); } @Override public DiscussionThreadBundle updateThreadMessage(String threadId, UpdateThreadMessage newMessage) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(newMessage, "newMessage"); return asymmetricalPut(repoEndpoint, THREAD+"/"+threadId+DISCUSSION_MESSAGE, newMessage, DiscussionThreadBundle.class); } @Override public void markThreadAsDeleted(String threadId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, THREAD+"/"+threadId, getUserAgent()); } @Override public void restoreDeletedThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+RESTORE, getUserAgent()); } @Override public DiscussionReplyBundle createReply(CreateDiscussionReply toCreate) throws SynapseException { ValidateArgument.required(toCreate, "toCreate"); return asymmetricalPost(repoEndpoint, REPLY, toCreate, DiscussionReplyBundle.class, null); } @Override public DiscussionReplyBundle getReply(String replyId) throws SynapseException { try { ValidateArgument.required(replyId, "replyId"); return getJSONEntity(REPLY+"/"+replyId, DiscussionReplyBundle.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionReplyBundle> getRepliesForThread( String threadId, Long limit, Long offset, DiscussionReplyOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = THREAD+"/"+threadId+REPLIES +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter; JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionReplyBundle> results = new PaginatedResults<DiscussionReplyBundle>(DiscussionReplyBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public DiscussionReplyBundle updateReplyMessage(String replyId, UpdateReplyMessage newMessage) throws SynapseException { ValidateArgument.required(replyId, "replyId"); ValidateArgument.required(newMessage, "newMessage"); return asymmetricalPut(repoEndpoint, REPLY+"/"+replyId+DISCUSSION_MESSAGE, newMessage, DiscussionReplyBundle.class); } @Override public void markReplyAsDeleted(String replyId) throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, REPLY+"/"+replyId, getUserAgent()); } @Override public MultipartUploadStatus startMultipartUpload( MultipartUploadRequest request, Boolean forceRestart) throws SynapseException { ValidateArgument.required(request, "MultipartUploadRequest"); StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("/file/multipart"); //the restart parameter is optional. if(forceRestart != null){ pathBuilder.append("?forceRestart="); pathBuilder.append(forceRestart.toString()); } return asymmetricalPost(fileEndpoint, pathBuilder.toString(), request, MultipartUploadStatus.class, null); } @Override public BatchPresignedUploadUrlResponse getMultipartPresignedUrlBatch( BatchPresignedUploadUrlRequest request) throws SynapseException { ValidateArgument.required(request, "BatchPresignedUploadUrlRequest"); ValidateArgument.required(request.getUploadId(), "BatchPresignedUploadUrlRequest.uploadId"); String path = String.format("/file/multipart/%1$s/presigned/url/batch", request.getUploadId()); return asymmetricalPost(fileEndpoint,path,request, BatchPresignedUploadUrlResponse.class, null); } @Override public AddPartResponse addPartToMultipartUpload(String uploadId, int partNumber, String partMD5Hex) throws SynapseException { ValidateArgument.required(uploadId, "uploadId"); ValidateArgument.required(partMD5Hex, "partMD5Hex"); String path = String.format("/file/multipart/%1$s/add/%2$d?partMD5Hex=%3$s", uploadId, partNumber, partMD5Hex); return asymmetricalPut(fileEndpoint, path, null, AddPartResponse.class); } @Override public MultipartUploadStatus completeMultipartUpload(String uploadId) throws SynapseException { ValidateArgument.required(uploadId, "uploadId"); String path = String.format("/file/multipart/%1$s/complete", uploadId); return asymmetricalPut(fileEndpoint, path, null, MultipartUploadStatus.class); } @Override public S3FileHandle multipartUpload(InputStream input, long fileSize, String fileName, String contentType, Long storageLocationId, Boolean generatePreview, Boolean forceRestart) throws SynapseException { return new MultipartUpload(this, input, fileSize, fileName, contentType, storageLocationId, generatePreview, forceRestart, new TempFileProviderImpl()).uploadFile(); } @Override public S3FileHandle multipartUpload(File file, Long storageLocationId, Boolean generatePreview, Boolean forceRestart) throws SynapseException, IOException { InputStream fileInputStream = null; try{ fileInputStream = new FileInputStream(file); String fileName = file.getName(); long fileSize = file.length(); String contentType = guessContentTypeFromStream(file); return multipartUpload(fileInputStream, fileSize, fileName, contentType, storageLocationId, generatePreview, forceRestart); }finally{ IOUtils.closeQuietly(fileInputStream); } } @Override public URL getReplyUrl(String messageKey) throws SynapseException { try { ValidateArgument.required(messageKey, "messageKey"); return new URL(getJSONEntity(REPLY+URL+"?messageKey="+messageKey, MessageURL.class).getMessageUrl()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } catch (MalformedURLException e) { throw new SynapseClientException(e); } } @Override public URL getThreadUrl(String messageKey) throws SynapseException { try { ValidateArgument.required(messageKey, "messageKey"); return new URL(getJSONEntity(THREAD+URL+"?messageKey="+messageKey, MessageURL.class).getMessageUrl()); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } catch (MalformedURLException e) { throw new SynapseClientException(e); } } @Override public Subscription subscribe(Topic toSubscribe) throws SynapseException { ValidateArgument.required(toSubscribe, "toSubscribe"); return asymmetricalPost(repoEndpoint, SUBSCRIPTION, toSubscribe, Subscription.class, null); } @Override public SubscriptionPagedResults getAllSubscriptions( SubscriptionObjectType objectType, Long limit, Long offset) throws SynapseException { try { ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(objectType, "objectType"); String url = SUBSCRIPTION+ALL+"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; url += "&"+OBJECT_TYPE_PARAM+"="+objectType.name(); return getJSONEntity(url, SubscriptionPagedResults.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public SubscriptionPagedResults listSubscriptions(SubscriptionRequest request) throws SynapseException { ValidateArgument.required(request, "request"); ValidateArgument.required(request.getObjectType(), "SubscriptionRequest.objectType"); ValidateArgument.required(request.getIdList(), "SubscriptionRequest.idList"); return asymmetricalPost(repoEndpoint, SUBSCRIPTION+LIST, request, SubscriptionPagedResults.class, null); } @Override public void unsubscribe(Long subscriptionId) throws SynapseException { ValidateArgument.required(subscriptionId, "subscriptionId"); getSharedClientConnection().deleteUri(repoEndpoint, SUBSCRIPTION+"/"+subscriptionId, getUserAgent()); } @Override public void unsubscribeAll() throws SynapseException { getSharedClientConnection().deleteUri(repoEndpoint, SUBSCRIPTION+ALL, getUserAgent()); } @Override public Subscription getSubscription(String subscriptionId) throws SynapseException { try { ValidateArgument.required(subscriptionId, "subscriptionId"); return getJSONEntity(SUBSCRIPTION+"/"+subscriptionId, Subscription.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public Etag getEtag(String objectId, ObjectType objectType) throws SynapseException { try { ValidateArgument.required(objectId, "objectId"); ValidateArgument.required(objectType, "objectType"); return getJSONEntity(OBJECT+"/"+objectId+"/"+objectType.name()+"/"+ETAG, Etag.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityId getEntityIdByAlias(String alias) throws SynapseException { ValidateArgument.required(alias, "alias"); try { return getJSONEntity(ENTITY+"/alias/"+alias, EntityId.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ThreadCount getThreadCountForForum(String forumId, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(filter, "filter"); String url = FORUM+"/"+forumId+THREAD_COUNT; url += "?filter="+filter; try { return getJSONEntity(url, ThreadCount.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public ReplyCount getReplyCountForThread(String threadId, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(threadId, "threadId"); ValidateArgument.required(filter, "filter"); String url = THREAD+"/"+threadId+REPLY_COUNT; url += "?filter="+filter; try { return getJSONEntity(url, ReplyCount.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public void pinThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+PIN, getUserAgent()); } @Override public void unpinThread(String threadId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, THREAD+"/"+threadId+UNPIN, getUserAgent()); } @Override public PrincipalAliasResponse getPrincipalAlias(PrincipalAliasRequest request) throws SynapseException { return asymmetricalPost(repoEndpoint, PRINCIPAL+"/alias/", request, PrincipalAliasResponse.class, null); } @Override public void addDockerCommit(String entityId, DockerCommit dockerCommit) throws SynapseException { ValidateArgument.required(entityId, "entityId"); try { JSONObject obj = EntityFactory.createJSONObjectForEntity(dockerCommit); getSharedClientConnection().postJson(repoEndpoint, ENTITY+"/"+entityId+DOCKER_COMMIT, obj.toString(), getUserAgent(), null); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DockerCommit> listDockerCommits( String entityId, Long limit, Long offset, DockerCommitSortBy sortBy, Boolean ascending) throws SynapseException { ValidateArgument.required(entityId, "entityId"); String url = ENTITY+"/"+entityId+DOCKER_COMMIT; List<String> requestParams = new ArrayList<String>(); if (limit!=null) requestParams.add(LIMIT+"="+limit); if (offset!=null) requestParams.add(OFFSET+"="+offset); if (sortBy!=null) requestParams.add("sort="+sortBy.name()); if (ascending!=null) requestParams.add("ascending="+ascending); if (!requestParams.isEmpty()) { url += "?" + Joiner.on('&').join(requestParams); } JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DockerCommit> results = new PaginatedResults<DockerCommit>( DockerCommit.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public PaginatedResults<DiscussionThreadBundle> getThreadsForEntity(String entityId, Long limit, Long offset, DiscussionThreadOrder order, Boolean ascending, DiscussionFilter filter) throws SynapseException { ValidateArgument.required(entityId, "entityId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); ValidateArgument.required(filter, "filter"); String url = ENTITY+"/"+entityId+THREADS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; if (order != null) { url += "&sort="+order.name(); } if (ascending != null) { url += "&ascending="+ascending; } url += "&filter="+filter.toString(); JSONObject jsonObj = getEntity(url); JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonObj); PaginatedResults<DiscussionThreadBundle> results = new PaginatedResults<DiscussionThreadBundle>(DiscussionThreadBundle.class); try { results.initializeFromJSONObject(adapter); return results; } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public EntityThreadCounts getEntityThreadCount(List<String> entityIds) throws SynapseException { EntityIdList idList = new EntityIdList(); idList.setIdList(entityIds); return asymmetricalPost(repoEndpoint, ENTITY_THREAD_COUNTS, idList , EntityThreadCounts.class, null); } @Override public PaginatedIds getModeratorsForForum(String forumId, Long limit, Long offset) throws SynapseException { ValidateArgument.required(forumId, "forumId"); ValidateArgument.required(limit, "limit"); ValidateArgument.required(offset, "offset"); String url = FORUM+"/"+forumId+MODERATORS +"?"+LIMIT+"="+limit+"&"+OFFSET+"="+offset; try { return getJSONEntity(url, PaginatedIds.class); } catch (JSONObjectAdapterException e) { throw new SynapseClientException(e); } } @Override public BatchFileResult getFileHandleAndUrlBatch(BatchFileRequest request) throws SynapseException { return asymmetricalPost(fileEndpoint, FILE_HANDLE_BATCH, request , BatchFileResult.class, null); } @Override public BatchFileHandleCopyResult copyFileHandles(BatchFileHandleCopyRequest request) throws SynapseException { return asymmetricalPost(fileEndpoint, FILE_HANDLES_COPY, request , BatchFileHandleCopyResult.class, null); } @Override public void requestToCancelSubmission(String submissionId) throws SynapseException { getSharedClientConnection().putUri(repoEndpoint, EVALUATION_URI_PATH+"/"+SUBMISSION+"/"+submissionId+"/cancellation", getUserAgent()); } @Override public void setUserIpAddress(String ipAddress) { getSharedClientConnection().setUserIp(ipAddress); } }
fix to allow retry of sending message
client/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseClientImpl.java
fix to allow retry of sending message
<ide><path>lient/synapseJavaClient/src/main/java/org/sagebionetworks/client/SynapseClientImpl.java <ide> @Override <ide> public MessageToUser sendStringMessage(MessageToUser message, <ide> String messageBody) throws SynapseException { <del> if (message.getFileHandleId() != null) <del> throw new IllegalArgumentException( <del> "Expected null fileHandleId but found " <del> + message.getFileHandleId()); <ide> String fileHandleId = uploadToFileHandle( <ide> messageBody.getBytes(MESSAGE_CHARSET), <ide> STRING_MESSAGE_CONTENT_TYPE); <ide> @Override <ide> public MessageToUser sendStringMessage(MessageToUser message, <ide> String entityId, String messageBody) throws SynapseException { <del> if (message.getFileHandleId() != null) <del> throw new IllegalArgumentException( <del> "Expected null fileHandleId but found " <del> + message.getFileHandleId()); <ide> String fileHandleId = uploadToFileHandle( <ide> messageBody.getBytes(MESSAGE_CHARSET), <ide> STRING_MESSAGE_CONTENT_TYPE);
Java
apache-2.0
3a90c1efa657145acff1dfacdb66f97d00c476ff
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.diagnostic.Dumpable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actions.EditorActionUtil; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.SelectionEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.editor.ex.FoldingModelEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.impl.event.DocumentEventImpl; import com.intellij.openapi.editor.impl.softwrap.SoftWrapHelper; import com.intellij.openapi.editor.impl.view.EditorPainter; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.DocumentUtil; import com.intellij.util.diff.FilesTooBigForDiffException; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.awt.*; import java.util.List; public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.CaretImpl"); private static final Key<CaretVisualAttributes> VISUAL_ATTRIBUTES_KEY = new Key<>("CaretAttributes"); private final EditorImpl myEditor; private boolean isValid = true; private LogicalPosition myLogicalCaret; private VerticalInfo myCaretInfo; private VisualPosition myVisibleCaret; private volatile PositionMarker myPositionMarker; private boolean myLeansTowardsLargerOffsets; private int myLogicalColumnAdjustment; int myVisualColumnAdjustment; private int myVisualLineStart; private int myVisualLineEnd; private boolean mySkipChangeRequests; /** * Initial horizontal caret position during vertical navigation. * Similar to {@link #myDesiredX}, but represents logical caret position ({@code getLogicalPosition().column}) rather than visual. */ private int myLastColumnNumber; private int myDesiredSelectionStartColumn = -1; private int myDesiredSelectionEndColumn = -1; /** * We check that caret is located at the target offset at the end of {@link #moveToOffset(int, boolean)} method. However, * it's possible that the following situation occurs: * <p/> * <pre> * <ol> * <li>Some client subscribes to caret change events;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} is called;</li> * <li>Caret position is changed during {@link #moveToLogicalPosition(LogicalPosition)} processing;</li> * <li>The client receives caret position change event and adjusts the position;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} processing is finished;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} reports an error because the caret is not located at the target offset;</li> * </ol> * </pre> * <p/> * This field serves as a flag that reports unexpected caret position change requests nested from {@link #moveToOffset(int, boolean)}. */ private boolean myReportCaretMoves; /** * This field holds initial horizontal caret position during vertical navigation. It's used to determine target position when * moving to the new line. It is stored in pixels, not in columns, to account for non-monospaced fonts as well. * <p/> * Negative value means no coordinate should be preserved. */ private int myDesiredX = -1; private volatile SelectionMarker mySelectionMarker; private volatile VisualPosition myRangeMarkerStartPosition; private volatile VisualPosition myRangeMarkerEndPosition; private volatile boolean myRangeMarkerEndPositionIsLead; private boolean myUnknownDirection; private int myDocumentUpdateCounter; CaretImpl(EditorImpl editor) { myEditor = editor; myLogicalCaret = new LogicalPosition(0, 0); myVisibleCaret = new VisualPosition(0, 0); myCaretInfo = new VerticalInfo(0, 0); myPositionMarker = new PositionMarker(0); myVisualLineStart = 0; Document doc = myEditor.getDocument(); myVisualLineEnd = doc.getLineCount() > 1 ? doc.getLineStartOffset(1) : doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0); myDocumentUpdateCounter = editor.getCaretModel().myDocumentUpdateCounter; } @Override public void moveToOffset(int offset) { moveToOffset(offset, false); } @Override public void moveToOffset(final int offset, final boolean locateBeforeSoftWrap) { assertIsDispatchThread(); validateCallContext(); if (mySkipChangeRequests) { return; } myEditor.getCaretModel().doWithCaretMerging(() -> { LogicalPosition logicalPosition = myEditor.offsetToLogicalPosition(offset); CaretEvent event = moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, null, true, false); final LogicalPosition positionByOffsetAfterMove = myEditor.offsetToLogicalPosition(getOffset()); if (!positionByOffsetAfterMove.equals(logicalPosition)) { StringBuilder debugBuffer = new StringBuilder(); moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, debugBuffer, true, true); int actualOffset = getOffset(); int textStart = Math.max(0, Math.min(offset, actualOffset) - 1); final DocumentEx document = myEditor.getDocument(); int textEnd = Math.min(document.getTextLength() - 1, Math.max(offset, actualOffset) + 1); CharSequence text = document.getCharsSequence().subSequence(textStart, textEnd); int inverseOffset = myEditor.logicalPositionToOffset(logicalPosition); LOG.error( "caret moved to wrong offset. Please submit a dedicated ticket and attach current editor's text to it.", new Throwable(), AttachmentFactory.createContext( "Requested: offset=" + offset + ", logical position='" + logicalPosition + "' but actual: offset=" + actualOffset + ", logical position='" + myLogicalCaret + "' (" + positionByOffsetAfterMove + "). " + myEditor.dumpState() + "\ninterested text [" + textStart + ";" + textEnd + "): '" + text + "'\n debug trace: " + debugBuffer + "\nLogical position -> offset ('" + logicalPosition + "'->'" + inverseOffset + "')")); } if (event != null) { myEditor.getCaretModel().fireCaretPositionChanged(event); EditorActionUtil.selectNonexpandableFold(myEditor); } }); } @NotNull @Override public CaretModel getCaretModel() { return myEditor.getCaretModel(); } @Override public boolean isValid() { return isValid; } @Override public void moveCaretRelatively(final int _columnShift, final int lineShift, final boolean withSelection, final boolean scrollToCaret) { assertIsDispatchThread(); if (mySkipChangeRequests) { return; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request", new Throwable()); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling()) { CopyPasteManager.getInstance().stopKillRings(); } myEditor.getCaretModel().doWithCaretMerging(() -> { updateCachedStateIfNeeded(); int oldOffset = getOffset(); int columnShift = _columnShift; if (withSelection && lineShift == 0) { if (columnShift == -1) { int column; while ((column = myVisibleCaret.column + columnShift - (hasSelection() && oldOffset == getSelectionEnd() ? 1 : 0)) >= 0 && myEditor.getInlayModel().hasInlineElementAt(new VisualPosition(myVisibleCaret.line, column))) { columnShift--; } } else if (columnShift == 1) { while (myEditor.getInlayModel().hasInlineElementAt( new VisualPosition(myVisibleCaret.line, myVisibleCaret.column + columnShift - (hasSelection() && oldOffset == getSelectionStart() ? 0 : 1)))) { columnShift++; } } } final int leadSelectionOffset = getLeadSelectionOffset(); final VisualPosition leadSelectionPosition = getLeadSelectionPosition(); EditorSettings editorSettings = myEditor.getSettings(); VisualPosition visualCaret = getVisualPosition(); int lastColumnNumber = myLastColumnNumber; int desiredX = myDesiredX; if (columnShift == 0) { if (myDesiredX < 0) { desiredX = getCurrentX(); } } else { myDesiredX = desiredX = -1; } int newLineNumber = visualCaret.line + lineShift; int newColumnNumber = visualCaret.column + columnShift; boolean newLeansRight = lineShift == 0 && columnShift != 0 ? columnShift < 0 : visualCaret.leansRight; if (desiredX >= 0) { newColumnNumber = myEditor.xyToVisualPosition(new Point(desiredX, Math.max(0, newLineNumber) * myEditor.getLineHeight())).column; } Document document = myEditor.getDocument(); if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) { int lastLine = document.getLineCount() - 1; if (lastLine < 0) lastLine = 0; if (newColumnNumber > EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber) && newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) { newColumnNumber = 0; newLineNumber++; } } else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) { if (newColumnNumber < 0 && newLineNumber > 0) { newLineNumber--; newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); } } if (newColumnNumber < 0) newColumnNumber = 0; // There is a possible case that caret is located at the first line and user presses 'Shift+Up'. We want to select all text // from the document start to the current caret position then. So, we have a dedicated flag for tracking that. boolean selectToDocumentStart = false; if (newLineNumber < 0) { selectToDocumentStart = true; newLineNumber = 0; // We want to move caret to the first column if it's already located at the first line and 'Up' is pressed. newColumnNumber = 0; } VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber); if (!myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber, newLeansRight)); int offset = myEditor.logicalPositionToOffset(log); if (offset >= document.getTextLength() && columnShift == 0) { int lastOffsetColumn = myEditor.offsetToVisualPosition(document.getTextLength(), true, false).column; // We want to move caret to the last column if if it's located at the last line and 'Down' is pressed. if (lastOffsetColumn > newColumnNumber) { newColumnNumber = lastOffsetColumn; newLeansRight = true; } } if (!editorSettings.isCaretInsideTabs()) { CharSequence text = document.getCharsSequence(); if (offset >= 0 && offset < document.getTextLength()) { if (text.charAt(offset) == '\t' && (columnShift <= 0 || offset == oldOffset)) { if (columnShift <= 0) { newColumnNumber = myEditor.offsetToVisualPosition(offset, true, false).column; } else { SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset + 1); // There is a possible case that tabulation symbol is the last document symbol represented on a visual line before // soft wrap. We can't just use column from 'offset + 1' because it would point on a next visual line. if (softWrap == null) { newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column; } else { newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); } } } } } } pos = new VisualPosition(newLineNumber, newColumnNumber, newLeansRight); if (columnShift != 0 && lineShift == 0 && myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { LogicalPosition logical = myEditor.visualToLogicalPosition(pos); int softWrapOffset = myEditor.logicalPositionToOffset(logical); if (columnShift >= 0) { moveToOffset(softWrapOffset); } else { int line = myEditor.offsetToVisualLine(softWrapOffset - 1); moveToVisualPosition(new VisualPosition(line, EditorUtil.getLastVisualLineColumnNumber(myEditor, line))); } } else { moveToVisualPosition(pos); if (!editorSettings.isVirtualSpace() && columnShift == 0 && lastColumnNumber >=0) { setLastColumnNumber(lastColumnNumber); } } if (withSelection) { if (selectToDocumentStart) { setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(0), 0); } else if (pos.line >= myEditor.getVisibleLineCount()) { int endOffset = document.getTextLength(); if (leadSelectionOffset < endOffset) { setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(endOffset), endOffset); } } else { int selectionStartToUse = leadSelectionOffset; VisualPosition selectionStartPositionToUse = leadSelectionPosition; if (isUnknownDirection() || oldOffset > getSelectionStart() && oldOffset < getSelectionEnd()) { if (getOffset() > leadSelectionOffset ^ getSelectionStart() < getSelectionEnd()) { selectionStartToUse = getSelectionEnd(); selectionStartPositionToUse = getSelectionEndPosition(); } else { selectionStartToUse = getSelectionStart(); selectionStartPositionToUse = getSelectionStartPosition(); } } setSelection(selectionStartPositionToUse, selectionStartToUse, getVisualPosition(), getOffset()); } } else { removeSelection(); } if (scrollToCaret) { myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } if (desiredX >= 0) { myDesiredX = desiredX; } EditorActionUtil.selectNonexpandableFold(myEditor); }); } @Override public void moveToLogicalPosition(@NotNull final LogicalPosition pos) { myEditor.getCaretModel().doWithCaretMerging(() -> moveToLogicalPosition(pos, false, null, false, true)); } private CaretEvent doMoveToLogicalPosition(@NotNull LogicalPosition pos, boolean locateBeforeSoftWrap, @NonNls @Nullable StringBuilder debugBuffer, boolean adjustForInlays, boolean fireListeners) { assertIsDispatchThread(); updateCachedStateIfNeeded(); if (debugBuffer != null) { debugBuffer.append("Start moveToLogicalPosition(). Locate before soft wrap: ").append(locateBeforeSoftWrap).append(", position: ") .append(pos).append("\n"); } myDesiredX = -1; validateCallContext(); int column = pos.column; int line = pos.line; boolean leansForward = pos.leansForward; Document doc = myEditor.getDocument(); int lineCount = doc.getLineCount(); if (lineCount == 0) { if (debugBuffer != null) { debugBuffer.append("Resetting target logical line to zero as the document is empty\n"); } line = 0; } else if (line > lineCount - 1) { if (debugBuffer != null) { debugBuffer.append("Resetting target logical line (").append(line).append(") to ").append(lineCount - 1) .append(" as it is greater than total document lines number\n"); } line = lineCount - 1; } EditorSettings editorSettings = myEditor.getSettings(); if (!editorSettings.isVirtualSpace() && line < lineCount) { int lineEndOffset = doc.getLineEndOffset(line); final LogicalPosition endLinePosition = myEditor.offsetToLogicalPosition(lineEndOffset); int lineEndColumnNumber = endLinePosition.column; if (column > lineEndColumnNumber) { int oldColumn = column; column = lineEndColumnNumber; leansForward = true; if (debugBuffer != null) { debugBuffer.append("Resetting target logical column (").append(oldColumn).append(") to ").append(lineEndColumnNumber) .append(" because caret is not allowed to be located after line end (offset: ").append(lineEndOffset).append(", ") .append("logical position: ").append(endLinePosition).append(").\n"); } } } myEditor.getFoldingModel().flushCaretPosition(this); VerticalInfo oldInfo = myCaretInfo; LogicalPosition oldCaretPosition = myLogicalCaret; VisualPosition oldVisualPosition = myVisibleCaret; LogicalPosition logicalPositionToUse = new LogicalPosition(line, column, leansForward); final int offset = myEditor.logicalPositionToOffset(logicalPositionToUse); if (debugBuffer != null) { debugBuffer.append("Resulting logical position to use: ").append(logicalPositionToUse).append(". It's mapped to offset ").append(offset).append("\n"); } FoldRegion collapsedAt = myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset); if (collapsedAt != null && offset > collapsedAt.getStartOffset()) { if (debugBuffer != null) { debugBuffer.append("Scheduling expansion of fold region ").append(collapsedAt).append("\n"); } Runnable runnable = () -> { FoldRegion[] allCollapsedAt = myEditor.getFoldingModel().fetchCollapsedAt(offset); for (FoldRegion foldRange : allCollapsedAt) { foldRange.setExpanded(true); } }; mySkipChangeRequests = true; try { myEditor.getFoldingModel().runBatchFoldingOperation(runnable, false); } finally { mySkipChangeRequests = false; } } setCurrentLogicalCaret(logicalPositionToUse); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myVisibleCaret = myEditor.logicalToVisualPosition(myLogicalCaret); myVisualColumnAdjustment = 0; updateOffsetsFromLogicalPosition(); int newOffset = getOffset(); if (debugBuffer != null) { debugBuffer.append("Storing offset ").append(newOffset).append(" (mapped from logical position ").append(myLogicalCaret).append(")\n"); } if (adjustForInlays) { VisualPosition correctPosition = EditorUtil.inlayAwareOffsetToVisualPosition(myEditor, newOffset); assert correctPosition.line == myVisibleCaret.line; myVisualColumnAdjustment = correctPosition.column - myVisibleCaret.column; myVisibleCaret = correctPosition; } updateVisualLineInfo(); myEditor.updateCaretCursor(); requestRepaint(oldInfo); if (locateBeforeSoftWrap && SoftWrapHelper.isCaretAfterSoftWrap(this)) { int lineToUse = myVisibleCaret.line - 1; if (lineToUse >= 0) { final VisualPosition visualPosition = new VisualPosition(lineToUse, EditorUtil.getLastVisualLineColumnNumber(myEditor, lineToUse)); if (debugBuffer != null) { debugBuffer.append("Adjusting caret position by moving it before soft wrap. Moving to visual position ").append(visualPosition).append("\n"); } final LogicalPosition logicalPosition = myEditor.visualToLogicalPosition(visualPosition); final int tmpOffset = myEditor.logicalPositionToOffset(logicalPosition); if (tmpOffset == newOffset) { boolean restore = myReportCaretMoves; myReportCaretMoves = false; try { moveToVisualPosition(visualPosition); return null; } finally { myReportCaretMoves = restore; } } else { LOG.error("Invalid editor dimension mapping", new Throwable(), AttachmentFactory.createContext( "Expected to map visual position '" + visualPosition + "' to offset " + newOffset + " but got the following: -> logical position '" + logicalPosition + "'; -> offset " + tmpOffset + ". State: " + myEditor.dumpState())); } } } if (!oldVisualPosition.equals(myVisibleCaret) || !oldCaretPosition.equals(myLogicalCaret)) { CaretEvent event = new CaretEvent(myEditor, this, oldCaretPosition, myLogicalCaret); if (fireListeners) { myEditor.getCaretModel().fireCaretPositionChanged(event); } else { return event; } } return null; } private void updateOffsetsFromLogicalPosition() { int offset = myEditor.logicalPositionToOffset(myLogicalCaret); myPositionMarker = new PositionMarker(offset); myLeansTowardsLargerOffsets = myLogicalCaret.leansForward; myLogicalColumnAdjustment = myLogicalCaret.column - myEditor.offsetToLogicalPosition(offset).column; } private void setLastColumnNumber(int lastColumnNumber) { myLastColumnNumber = lastColumnNumber; } private void requestRepaint(VerticalInfo oldCaretInfo) { int lineHeight = myEditor.getLineHeight(); Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea(); final EditorGutterComponentEx gutter = myEditor.getGutterComponentEx(); final EditorComponentImpl content = myEditor.getContentComponent(); int updateWidth = myEditor.getScrollPane().getHorizontalScrollBar().getValue() + visibleArea.width; int additionalRepaintHeight = this == myEditor.getCaretModel().getPrimaryCaret() && Registry.is("editor.adjust.right.margin") && EditorPainter.isMarginShown(myEditor) ? 1 : 0; if (Math.abs(myCaretInfo.y - oldCaretInfo.y) <= 2 * lineHeight) { int minY = Math.min(oldCaretInfo.y, myCaretInfo.y); int maxY = Math.max(oldCaretInfo.y + oldCaretInfo.height, myCaretInfo.y + myCaretInfo.height); content.repaintEditorComponent(0, minY - additionalRepaintHeight, updateWidth, maxY - minY + additionalRepaintHeight); gutter.repaint(0, minY, gutter.getWidth(), maxY - minY); } else { content.repaintEditorComponent(0, oldCaretInfo.y - additionalRepaintHeight, updateWidth, oldCaretInfo.height + lineHeight + additionalRepaintHeight); gutter.repaint(0, oldCaretInfo.y, updateWidth, oldCaretInfo.height + lineHeight); content.repaintEditorComponent(0, myCaretInfo.y - additionalRepaintHeight, updateWidth, myCaretInfo.height + lineHeight + additionalRepaintHeight); gutter.repaint(0, myCaretInfo.y, updateWidth, myCaretInfo.height + lineHeight); } } @Override public void moveToVisualPosition(@NotNull final VisualPosition pos) { myEditor.getCaretModel().doWithCaretMerging(() -> moveToVisualPosition(pos, true)); } void moveToVisualPosition(@NotNull VisualPosition pos, boolean fireListeners) { assertIsDispatchThread(); validateCallContext(); if (mySkipChangeRequests) { return; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request"); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling() && !pos.equals(myVisibleCaret)) { CopyPasteManager.getInstance().stopKillRings(); } updateCachedStateIfNeeded(); myDesiredX = -1; int column = pos.column; int line = pos.line; boolean leanRight = pos.leansRight; int lastLine = myEditor.getVisibleLineCount() - 1; if (lastLine <= 0) { lastLine = 0; } if (line > lastLine) { line = lastLine; } EditorSettings editorSettings = myEditor.getSettings(); if (!editorSettings.isVirtualSpace()) { int lineEndColumn = EditorUtil.getLastVisualLineColumnNumber(myEditor, line); if (column > lineEndColumn && !myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { column = lineEndColumn; leanRight = true; } } VisualPosition oldVisualPosition = myVisibleCaret; myVisibleCaret = new VisualPosition(line, column, leanRight); VerticalInfo oldInfo = myCaretInfo; LogicalPosition oldPosition = myLogicalCaret; setCurrentLogicalCaret(myEditor.visualToLogicalPosition(myVisibleCaret)); VisualPosition mappedPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisualColumnAdjustment = mappedPosition.line == myVisibleCaret.line && myVisibleCaret.column > mappedPosition.column && !myLogicalCaret.leansForward ? myVisibleCaret.column - mappedPosition.column : 0; updateOffsetsFromLogicalPosition(); updateVisualLineInfo(); myEditor.getFoldingModel().flushCaretPosition(this); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myEditor.updateCaretCursor(); requestRepaint(oldInfo); if (fireListeners && (!oldPosition.equals(myLogicalCaret) || !oldVisualPosition.equals(myVisibleCaret))) { CaretEvent event = new CaretEvent(myEditor, this, oldPosition, myLogicalCaret); myEditor.getCaretModel().fireCaretPositionChanged(event); } } @Nullable CaretEvent moveToLogicalPosition(@NotNull LogicalPosition pos, boolean locateBeforeSoftWrap, @Nullable StringBuilder debugBuffer, boolean adjustForInlays, boolean fireListeners) { if (mySkipChangeRequests) { return null; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request"); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling() && !pos.equals(myLogicalCaret)) { CopyPasteManager.getInstance().stopKillRings(); } myReportCaretMoves = true; try { return doMoveToLogicalPosition(pos, locateBeforeSoftWrap, debugBuffer, adjustForInlays, fireListeners); } finally { myReportCaretMoves = false; } } private static void assertIsDispatchThread() { EditorImpl.assertIsDispatchThread(); } private void validateCallContext() { LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread() || !myEditor.getCaretModel().myIsInUpdate, "Caret model is in its update process. All requests are illegal at this point."); } @Override public void dispose() { if (myPositionMarker != null) { myPositionMarker = null; } if (mySelectionMarker != null) { mySelectionMarker = null; } isValid = false; } @Override public boolean isUpToDate() { return !myEditor.getCaretModel().myIsInUpdate && !myReportCaretMoves; } @NotNull @Override public LogicalPosition getLogicalPosition() { validateCallContext(); updateCachedStateIfNeeded(); return myLogicalCaret; } @NotNull @Override public VisualPosition getVisualPosition() { validateCallContext(); updateCachedStateIfNeeded(); return myVisibleCaret; } @Override public int getOffset() { validateCallContext(); validateContext(false); PositionMarker marker = myPositionMarker; if (marker == null) return 0; // caret was disposed assert marker.isValid(); return marker.getStartOffset(); } @Override public int getVisualLineStart() { updateCachedStateIfNeeded(); return myVisualLineStart; } @Override public int getVisualLineEnd() { updateCachedStateIfNeeded(); return myVisualLineEnd; } @NotNull private VerticalInfo createVerticalInfo(LogicalPosition position) { Document document = myEditor.getDocument(); int logicalLine = position.line; if (logicalLine >= document.getLineCount()) { logicalLine = Math.max(0, document.getLineCount() - 1); } int startOffset = document.getLineStartOffset(logicalLine); int endOffset = document.getLineEndOffset(logicalLine); // There is a possible case that active logical line is represented on multiple lines due to soft wraps processing. // We want to highlight those visual lines as 'active' then, so, we calculate 'y' position for the logical line start // and height in accordance with the number of occupied visual lines. int visualLine = myEditor.offsetToVisualLine(document.getLineStartOffset(logicalLine)); int y = myEditor.visibleLineToY(visualLine); int lineHeight = myEditor.getLineHeight(); int height = lineHeight; List<? extends SoftWrap> softWraps = myEditor.getSoftWrapModel().getSoftWrapsForRange(startOffset, endOffset); for (SoftWrap softWrap : softWraps) { height += StringUtil.countNewLines(softWrap.getText()) * lineHeight; } return new VerticalInfo(y, height); } /** * Recalculates caret visual position without changing its logical position (called when soft wraps are changing) */ void updateVisualPosition() { updateCachedStateIfNeeded(); VerticalInfo oldInfo = myCaretInfo; LogicalPosition visUnawarePos = new LogicalPosition(myLogicalCaret.line, myLogicalCaret.column, myLogicalCaret.leansForward); setCurrentLogicalCaret(visUnawarePos); VisualPosition visualPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisibleCaret = new VisualPosition(visualPosition.line, visualPosition.column + myVisualColumnAdjustment, visualPosition.leansRight); updateVisualLineInfo(); myEditor.updateCaretCursor(); requestRepaint(oldInfo); } private void updateVisualLineInfo() { myVisualLineStart = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0))); myVisualLineEnd = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0))); } void onInlayAdded(int offset) { updateCachedStateIfNeeded(); int currentOffset = getOffset(); if (offset == currentOffset) { VisualPosition pos = EditorUtil.inlayAwareOffsetToVisualPosition(myEditor, offset); moveToVisualPosition(pos); } else { updateVisualPosition(); } } void onInlayRemoved(int offset, int order) { int currentOffset = getOffset(); if (offset == currentOffset && myVisualColumnAdjustment > 0 && myVisualColumnAdjustment > order) myVisualColumnAdjustment--; updateVisualPosition(); } private void setCurrentLogicalCaret(@NotNull LogicalPosition position) { myLogicalCaret = position; myCaretInfo = createVerticalInfo(position); } int getWordAtCaretStart() { Document document = myEditor.getDocument(); int offset = getOffset(); if (offset == 0) return 0; int lineNumber = getLogicalPosition().line; int newOffset = offset - 1; int minOffset = lineNumber > 0 ? document.getLineEndOffset(lineNumber - 1) : 0; boolean camel = myEditor.getSettings().isCamelWords(); for (; newOffset > minOffset; newOffset--) { if (EditorActionUtil.isWordOrLexemeStart(myEditor, newOffset, camel)) break; } return newOffset; } int getWordAtCaretEnd() { Document document = myEditor.getDocument(); int offset = getOffset(); if (offset >= document.getTextLength() - 1 || document.getLineCount() == 0) return offset; int newOffset = offset + 1; int lineNumber = getLogicalPosition().line; int maxOffset = document.getLineEndOffset(lineNumber); if (newOffset > maxOffset) { if (lineNumber + 1 >= document.getLineCount()) return offset; maxOffset = document.getLineEndOffset(lineNumber + 1); } boolean camel = myEditor.getSettings().isCamelWords(); for (; newOffset < maxOffset; newOffset++) { if (EditorActionUtil.isWordOrLexemeEnd(myEditor, newOffset, camel)) break; } return newOffset; } private CaretImpl cloneWithoutSelection() { updateCachedStateIfNeeded(); CaretImpl clone = new CaretImpl(myEditor); clone.myLogicalCaret = myLogicalCaret; clone.myCaretInfo = myCaretInfo; clone.myVisibleCaret = myVisibleCaret; clone.myPositionMarker = new PositionMarker(getOffset()); clone.myLeansTowardsLargerOffsets = myLeansTowardsLargerOffsets; clone.myLogicalColumnAdjustment = myLogicalColumnAdjustment; clone.myVisualColumnAdjustment = myVisualColumnAdjustment; clone.myVisualLineStart = myVisualLineStart; clone.myVisualLineEnd = myVisualLineEnd; clone.mySkipChangeRequests = mySkipChangeRequests; clone.myLastColumnNumber = myLastColumnNumber; clone.myReportCaretMoves = myReportCaretMoves; clone.myDesiredX = myDesiredX; clone.myDesiredSelectionStartColumn = -1; clone.myDesiredSelectionEndColumn = -1; return clone; } @Nullable @Override public Caret clone(boolean above) { assertIsDispatchThread(); int lineShift = above ? -1 : 1; LogicalPosition oldPosition = getLogicalPosition(); int newLine = oldPosition.line + lineShift; if (newLine < 0 || newLine >= myEditor.getDocument().getLineCount()) { return null; } final CaretImpl clone = cloneWithoutSelection(); final int newSelectionStartOffset; final int newSelectionEndOffset; final int newSelectionStartColumn; final int newSelectionEndColumn; final VisualPosition newSelectionStartPosition; final VisualPosition newSelectionEndPosition; final boolean hasNewSelection; if (hasSelection() || myDesiredSelectionStartColumn >=0 || myDesiredSelectionEndColumn >= 0) { VisualPosition startPosition = getSelectionStartPosition(); VisualPosition endPosition = getSelectionEndPosition(); VisualPosition leadPosition = getLeadSelectionPosition(); boolean leadIsStart = leadPosition.equals(startPosition); boolean leadIsEnd = leadPosition.equals(endPosition); LogicalPosition selectionStart = myEditor.visualToLogicalPosition(leadIsStart || leadIsEnd ? leadPosition : startPosition); LogicalPosition selectionEnd = myEditor.visualToLogicalPosition(leadIsEnd ? startPosition : endPosition); newSelectionStartColumn = myDesiredSelectionStartColumn < 0 ? selectionStart.column : myDesiredSelectionStartColumn; newSelectionEndColumn = myDesiredSelectionEndColumn < 0 ? selectionEnd.column : myDesiredSelectionEndColumn; LogicalPosition newSelectionStart = truncate(selectionStart.line + lineShift, newSelectionStartColumn); LogicalPosition newSelectionEnd = truncate(selectionEnd.line + lineShift, newSelectionEndColumn); newSelectionStartOffset = myEditor.logicalPositionToOffset(newSelectionStart); newSelectionEndOffset = myEditor.logicalPositionToOffset(newSelectionEnd); newSelectionStartPosition = myEditor.logicalToVisualPosition(newSelectionStart); newSelectionEndPosition = myEditor.logicalToVisualPosition(newSelectionEnd); hasNewSelection = !newSelectionStart.equals(newSelectionEnd); } else { newSelectionStartOffset = 0; newSelectionEndOffset = 0; newSelectionStartPosition = null; newSelectionEndPosition = null; hasNewSelection = false; newSelectionStartColumn = -1; newSelectionEndColumn = -1; } clone.moveToLogicalPosition(new LogicalPosition(newLine, myLastColumnNumber), false, null, false, false); clone.myLastColumnNumber = myLastColumnNumber; clone.myDesiredX = myDesiredX >= 0 ? myDesiredX : getCurrentX(); clone.myDesiredSelectionStartColumn = newSelectionStartColumn; clone.myDesiredSelectionEndColumn = newSelectionEndColumn; if (myEditor.getCaretModel().addCaret(clone, true)) { if (hasNewSelection) { myEditor.getCaretModel().doWithCaretMerging( () -> clone.setSelection(newSelectionStartPosition, newSelectionStartOffset, newSelectionEndPosition, newSelectionEndOffset)); if (!clone.isValid()) { return null; } } myEditor.getScrollingModel().scrollTo(clone.getLogicalPosition(), ScrollType.RELATIVE); return clone; } else { Disposer.dispose(clone); return null; } } private LogicalPosition truncate(int line, int column) { if (line < 0) { return new LogicalPosition(0, 0); } else if (line >= myEditor.getDocument().getLineCount()) { return myEditor.offsetToLogicalPosition(myEditor.getDocument().getTextLength()); } else { return new LogicalPosition(line, column); } } /** * @return information on whether current selection's direction in known * @see #setUnknownDirection(boolean) */ boolean isUnknownDirection() { return myUnknownDirection; } /** * There is a possible case that we don't know selection's direction. For example, a user might triple-click editor (select the * whole line). We can't say what selection end is a {@link #getLeadSelectionOffset() leading end} then. However, that matters * in a situation when a user clicks before or after that line holding Shift key. It's expected that the selection is expanded * up to that point than. * <p/> * That's why we allow to specify that the direction is unknown and {@link #isUnknownDirection() expose this information} * later. * <p/> * <b>Note:</b> when this method is called with {@code 'true'}, subsequent calls are guaranteed to return {@code true} * until selection is changed. 'Unknown direction' flag is automatically reset then. * */ void setUnknownDirection(boolean unknownDirection) { myUnknownDirection = unknownDirection; } @Override public int getSelectionStart() { validateContext(false); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null) { return marker.getStartOffset(); } } return getOffset(); } @NotNull @Override public VisualPosition getSelectionStartPosition() { validateContext(true); VisualPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { position = getRangeMarkerStartPosition(); if (position == null) { VisualPosition startPosition = myEditor.offsetToVisualPosition(marker.getStartOffset(), true, false); VisualPosition endPosition = myEditor.offsetToVisualPosition(marker.getEndOffset(), false, true); position = startPosition.after(endPosition) ? endPosition : startPosition; } } else { position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset(), getLogicalPosition().leansForward, false); } if (hasVirtualSelection()) { position = new VisualPosition(position.line, position.column + marker.startVirtualOffset); } return position; } LogicalPosition getSelectionStartLogicalPosition() { validateContext(true); LogicalPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { VisualPosition visualPosition = getRangeMarkerStartPosition(); position = visualPosition == null ? myEditor.offsetToLogicalPosition(marker.getStartOffset()).leanForward(true) : myEditor.visualToLogicalPosition(visualPosition); } else { position = getLogicalPosition(); } if (hasVirtualSelection()) { position = new LogicalPosition(position.line, position.column + marker.startVirtualOffset); } return position; } @Override public int getSelectionEnd() { validateContext(false); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null) { return marker.getEndOffset(); } } return getOffset(); } @NotNull @Override public VisualPosition getSelectionEndPosition() { validateContext(true); VisualPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { position = getRangeMarkerEndPosition(); if (position == null) { VisualPosition startPosition = myEditor.offsetToVisualPosition(marker.getStartOffset(), true, false); VisualPosition endPosition = myEditor.offsetToVisualPosition(marker.getEndOffset(), false, true); position = startPosition.after(endPosition) ? startPosition : endPosition; } } else { position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset(), getLogicalPosition().leansForward, false); } if (hasVirtualSelection()) { position = new VisualPosition(position.line, position.column + marker.endVirtualOffset); } return position; } LogicalPosition getSelectionEndLogicalPosition() { validateContext(true); LogicalPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { VisualPosition visualPosition = getRangeMarkerEndPosition(); position = visualPosition == null ? myEditor.offsetToLogicalPosition(marker.getEndOffset()) : myEditor.visualToLogicalPosition(visualPosition); } else { position = getLogicalPosition(); } if (hasVirtualSelection()) { position = new LogicalPosition(position.line, position.column + marker.endVirtualOffset); } return position; } @Override public boolean hasSelection() { validateContext(false); SelectionMarker marker = mySelectionMarker; return marker != null && marker.isValid() && (marker.getEndOffset() > marker.getStartOffset() || isVirtualSelectionEnabled() && marker.hasVirtualSelection()); } @Override public void setSelection(int startOffset, int endOffset) { setSelection(startOffset, endOffset, true); } @Override public void setSelection(int startOffset, int endOffset, boolean updateSystemSelection) { doSetSelection(myEditor.offsetToVisualPosition(startOffset, true, false), startOffset, myEditor.offsetToVisualPosition(endOffset, false, true), endOffset, false, updateSystemSelection, true); } @Override public void setSelection(int startOffset, @Nullable VisualPosition endPosition, int endOffset) { VisualPosition startPosition; if (hasSelection()) { startPosition = getLeadSelectionPosition(); } else { startPosition = myEditor.offsetToVisualPosition(startOffset, true, false); } setSelection(startPosition, startOffset, endPosition, endOffset); } @Override public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset) { setSelection(startPosition, startOffset, endPosition, endOffset, true); } @Override public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset, boolean updateSystemSelection) { VisualPosition startPositionToUse = startPosition == null ? myEditor.offsetToVisualPosition(startOffset, true, false) : startPosition; VisualPosition endPositionToUse = endPosition == null ? myEditor.offsetToVisualPosition(endOffset, false, true) : endPosition; doSetSelection(startPositionToUse, startOffset, endPositionToUse, endOffset, true, updateSystemSelection, true); } void doSetSelection(@NotNull final VisualPosition startPosition, final int _startOffset, @NotNull final VisualPosition endPosition, final int _endOffset, final boolean visualPositionAware, final boolean updateSystemSelection, final boolean fireListeners) { myEditor.getCaretModel().doWithCaretMerging(() -> { int startOffset = DocumentUtil.alignToCodePointBoundary(myEditor.getDocument(), _startOffset); int endOffset = DocumentUtil.alignToCodePointBoundary(myEditor.getDocument(), _endOffset); myUnknownDirection = false; final Document doc = myEditor.getDocument(); validateContext(true); int textLength = doc.getTextLength(); if (startOffset < 0 || startOffset > textLength) { LOG.error("Wrong startOffset: " + startOffset + ", textLength=" + textLength); } if (endOffset < 0 || endOffset > textLength) { LOG.error("Wrong endOffset: " + endOffset + ", textLength=" + textLength); } if (!visualPositionAware && startOffset == endOffset) { removeSelection(); return; } /* Normalize selection */ boolean switchedOffsets = false; if (startOffset > endOffset) { int tmp = startOffset; startOffset = endOffset; endOffset = tmp; switchedOffsets = true; } FoldingModelEx foldingModel = myEditor.getFoldingModel(); FoldRegion startFold = foldingModel.getCollapsedRegionAtOffset(startOffset); if (startFold != null && startFold.getStartOffset() < startOffset) { startOffset = startFold.getStartOffset(); } FoldRegion endFold = foldingModel.getCollapsedRegionAtOffset(endOffset); if (endFold != null && endFold.getStartOffset() < endOffset) { // All visual positions that lay at collapsed fold region placeholder are mapped to the same offset. Hence, there are // at least two distinct situations - selection end is located inside collapsed fold region placeholder and just before it. // We want to expand selection to the fold region end at the former case and keep selection as-is at the latest one. endOffset = endFold.getEndOffset(); } int oldSelectionStart; int oldSelectionEnd; if (hasSelection()) { oldSelectionStart = getSelectionStart(); oldSelectionEnd = getSelectionEnd(); if (oldSelectionStart == startOffset && oldSelectionEnd == endOffset && !visualPositionAware) return; } else { oldSelectionStart = oldSelectionEnd = getOffset(); } SelectionMarker marker = new SelectionMarker(startOffset, endOffset); if (visualPositionAware) { if (endPosition.after(startPosition)) { setRangeMarkerStartPosition(startPosition); setRangeMarkerEndPosition(endPosition); setRangeMarkerEndPositionIsLead(false); } else { setRangeMarkerStartPosition(endPosition); setRangeMarkerEndPosition(startPosition); setRangeMarkerEndPositionIsLead(true); } if (isVirtualSelectionEnabled() && myEditor.getDocument().getLineNumber(startOffset) == myEditor.getDocument().getLineNumber(endOffset)) { int endLineColumn = myEditor.offsetToVisualPosition(endOffset).column; int startDiff = EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? endOffset : startOffset) ? startPosition.column - endLineColumn : 0; int endDiff = EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? startOffset : endOffset) ? endPosition.column - endLineColumn : 0; marker.startVirtualOffset = Math.max(0, Math.min(startDiff, endDiff)); marker.endVirtualOffset = Math.max(0, Math.max(startDiff, endDiff)); } } mySelectionMarker = marker; if (fireListeners) { myEditor.getSelectionModel().fireSelectionChanged(new SelectionEvent(myEditor, oldSelectionStart, oldSelectionEnd, startOffset, endOffset)); } if (updateSystemSelection) { myEditor.getCaretModel().updateSystemSelection(); } }); } @Override public void removeSelection() { if (myEditor.isStickySelection()) { // Most of our 'change caret position' actions (like move caret to word start/end etc) remove active selection. // However, we don't want to do that for 'sticky selection'. return; } myEditor.getCaretModel().doWithCaretMerging(() -> { validateContext(true); int caretOffset = getOffset(); RangeMarker marker = mySelectionMarker; if (marker != null && marker.isValid()) { int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); mySelectionMarker = null; myEditor.getSelectionModel().fireSelectionChanged(new SelectionEvent(myEditor, startOffset, endOffset, caretOffset, caretOffset)); } }); } @Override public int getLeadSelectionOffset() { validateContext(false); int caretOffset = getOffset(); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null && marker.isValid()) { int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); if (caretOffset != startOffset && caretOffset != endOffset) { // Try to check if current selection is tweaked by fold region. FoldingModelEx foldingModel = myEditor.getFoldingModel(); FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(caretOffset); if (foldRegion != null) { if (foldRegion.getStartOffset() == startOffset) { return endOffset; } else if (foldRegion.getEndOffset() == endOffset) { return startOffset; } } } if (caretOffset == endOffset) { return startOffset; } else { return endOffset; } } } return caretOffset; } @NotNull @Override public VisualPosition getLeadSelectionPosition() { SelectionMarker marker = mySelectionMarker; VisualPosition caretPosition = getVisualPosition(); if (isVirtualSelectionEnabled() && !hasSelection()) { return caretPosition; } if (marker == null || !marker.isValid()) { return caretPosition; } if (isRangeMarkerEndPositionIsLead()) { VisualPosition result = getRangeMarkerEndPosition(); if (result == null) { return getSelectionEndPosition(); } else { if (hasVirtualSelection()) { result = new VisualPosition(result.line, result.column + marker.endVirtualOffset); } return result; } } else { VisualPosition result = getRangeMarkerStartPosition(); if (result == null) { return getSelectionStartPosition(); } else { if (hasVirtualSelection()) { result = new VisualPosition(result.line, result.column + marker.startVirtualOffset); } return result; } } } @Override public void selectLineAtCaret() { validateContext(true); myEditor.getCaretModel().doWithCaretMerging(() -> SelectionModelImpl.doSelectLineAtCaret(this)); } @Override public void selectWordAtCaret(final boolean honorCamelWordsSettings) { validateContext(true); myEditor.getCaretModel().doWithCaretMerging(() -> { removeSelection(); final EditorSettings settings = myEditor.getSettings(); boolean camelTemp = settings.isCamelWords(); final boolean needOverrideSetting = camelTemp && !honorCamelWordsSettings; if (needOverrideSetting) { settings.setCamelWords(false); } try { EditorAction action = (EditorAction)ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); action.actionPerformed(myEditor, myEditor.getDataContext()); } finally { if (needOverrideSetting) { settings.resetCamelWords(); } } }); } @Nullable @Override public String getSelectedText() { if (!hasSelection()) { return null; } SelectionMarker selectionMarker = mySelectionMarker; CharSequence text = myEditor.getDocument().getCharsSequence(); int selectionStart = getSelectionStart(); int selectionEnd = getSelectionEnd(); String selectedText = text.subSequence(selectionStart, selectionEnd).toString(); if (isVirtualSelectionEnabled() && selectionMarker.hasVirtualSelection()) { int padding = selectionMarker.endVirtualOffset - selectionMarker.startVirtualOffset; StringBuilder builder = new StringBuilder(selectedText.length() + padding); builder.append(selectedText); for (int i = 0; i < padding; i++) { builder.append(' '); } return builder.toString(); } else { return selectedText; } } private static void validateContext(boolean requireEdt) { if (requireEdt) { ApplicationManager.getApplication().assertIsDispatchThread(); } else { ApplicationManager.getApplication().assertReadAccessAllowed(); } } private boolean isVirtualSelectionEnabled() { return myEditor.isColumnMode(); } boolean hasVirtualSelection() { validateContext(false); SelectionMarker marker = mySelectionMarker; return marker != null && marker.isValid() && isVirtualSelectionEnabled() && marker.hasVirtualSelection(); } void resetVirtualSelection() { SelectionMarker marker = mySelectionMarker; if (marker != null) marker.resetVirtualSelection(); } private int getCurrentX() { return myEditor.visualPositionToXY(myVisibleCaret).x; } @Override @NotNull public EditorImpl getEditor() { return myEditor; } @Override public String toString() { return "Caret at " + (myDocumentUpdateCounter == myEditor.getCaretModel().myDocumentUpdateCounter ? myVisibleCaret : getOffset()) + (mySelectionMarker == null ? "" : ", selection marker: " + mySelectionMarker); } @Override public boolean isAtRtlLocation() { return myEditor.myView.isRtlLocation(getVisualPosition()); } @Override public boolean isAtBidiRunBoundary() { return myEditor.myView.isAtBidiRunBoundary(getVisualPosition()); } @NotNull @Override public CaretVisualAttributes getVisualAttributes() { CaretVisualAttributes attrs = getUserData(VISUAL_ATTRIBUTES_KEY); return attrs == null ? CaretVisualAttributes.DEFAULT : attrs; } @Override public void setVisualAttributes(@NotNull CaretVisualAttributes attributes) { putUserData(VISUAL_ATTRIBUTES_KEY, attributes == CaretVisualAttributes.DEFAULT ? null : attributes); requestRepaint(myCaretInfo); } @NotNull @Override public String dumpState() { return "{valid: " + isValid + ", update counter: " + myDocumentUpdateCounter + ", position: " + myPositionMarker + ", logical pos: " + myLogicalCaret + ", visual pos: " + myVisibleCaret + ", visual line start: " + myVisualLineStart + ", visual line end: " + myVisualLineEnd + ", skip change requests: " + mySkipChangeRequests + ", desired selection start column: " + myDesiredSelectionStartColumn + ", desired selection end column: " + myDesiredSelectionEndColumn + ", report caret moves: " + myReportCaretMoves + ", desired x: " + myDesiredX + ", selection marker: " + mySelectionMarker + ", rangeMarker start position: " + myRangeMarkerStartPosition + ", rangeMarker end position: " + myRangeMarkerEndPosition + ", rangeMarker end position is lead: " + myRangeMarkerEndPositionIsLead + ", unknown direction: " + myUnknownDirection + ", logical column adjustment: " + myLogicalColumnAdjustment + ", visual column adjustment: " + myVisualColumnAdjustment + '}'; } /** * Encapsulates information about target vertical range info - its {@code 'y'} coordinate and height in pixels. */ private static class VerticalInfo { public final int y; public final int height; private VerticalInfo(int y, int height) { this.y = y; this.height = height; } } @Nullable private VisualPosition getRangeMarkerStartPosition() { invalidateRangeMarkerVisualPositions(mySelectionMarker); return myRangeMarkerStartPosition; } private void setRangeMarkerStartPosition(@NotNull VisualPosition startPosition) { myRangeMarkerStartPosition = startPosition; } @Nullable private VisualPosition getRangeMarkerEndPosition() { invalidateRangeMarkerVisualPositions(mySelectionMarker); return myRangeMarkerEndPosition; } private void setRangeMarkerEndPosition(@NotNull VisualPosition endPosition) { myRangeMarkerEndPosition = endPosition; } private boolean isRangeMarkerEndPositionIsLead() { return myRangeMarkerEndPositionIsLead; } private void setRangeMarkerEndPositionIsLead(boolean endPositionIsLead) { myRangeMarkerEndPositionIsLead = endPositionIsLead; } private void invalidateRangeMarkerVisualPositions(RangeMarker marker) { SoftWrapModelImpl model = myEditor.getSoftWrapModel(); InlayModelImpl inlayModel = myEditor.getInlayModel(); int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); if ((myRangeMarkerStartPosition == null || !myEditor.offsetToVisualPosition(startOffset, true, false).equals(myRangeMarkerStartPosition)) && model.getSoftWrap(startOffset) == null && !inlayModel.hasInlineElementAt(startOffset) || (myRangeMarkerEndPosition == null || !myEditor.offsetToVisualPosition(endOffset, false, true).equals(myRangeMarkerEndPosition)) && model.getSoftWrap(endOffset) == null && !inlayModel.hasInlineElementAt(endOffset)) { myRangeMarkerStartPosition = null; myRangeMarkerEndPosition = null; } } void updateCachedStateIfNeeded() { if (!ApplicationManager.getApplication().isDispatchThread()) return; int modelCounter = myEditor.getCaretModel().myDocumentUpdateCounter; if (myDocumentUpdateCounter != modelCounter) { LogicalPosition lp = myEditor.offsetToLogicalPosition(getOffset()); setCurrentLogicalCaret(new LogicalPosition(lp.line, lp.column + myLogicalColumnAdjustment, myLeansTowardsLargerOffsets)); VisualPosition visualPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisibleCaret = new VisualPosition(visualPosition.line, visualPosition.column + myVisualColumnAdjustment, visualPosition.leansRight); updateVisualLineInfo(); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myDesiredX = -1; myDocumentUpdateCounter = modelCounter; } } @TestOnly public void validateState() { LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getOffset())); LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getSelectionStart())); LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getSelectionEnd())); } class PositionMarker extends RangeMarkerImpl { private PositionMarker(int offset) { super(myEditor.getDocument(), offset, offset, false); myEditor.getCaretModel().myPositionMarkerTree.addInterval(this, offset, offset, false, false, false, 0); } @Override public void dispose() { if (isValid()) { myEditor.getCaretModel().myPositionMarkerTree.removeInterval(this); } } @Override protected void changedUpdateImpl(@NotNull DocumentEvent e) { int oldOffset = intervalStart(); super.changedUpdateImpl(e); if (isValid()) { // Under certain conditions, when text is inserted at caret position, we position caret at the end of inserted text. // Ideally, client code should be responsible for positioning caret after document modification, but in case of // postponed formatting (after PSI modifications), this is hard to implement, so a heuristic below is used. if (e.getOldLength() == 0 && oldOffset == e.getOffset() && !Boolean.TRUE.equals(myEditor.getUserData(EditorImpl.DISABLE_CARET_SHIFT_ON_WHITESPACE_INSERTION)) && needToShiftWhiteSpaces(e)) { int afterInserted = e.getOffset() + e.getNewLength(); setIntervalStart(afterInserted); setIntervalEnd(afterInserted); } int offset = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), offset)) { setIntervalStart(offset - 1); setIntervalEnd(offset - 1); } } else { setValid(true); int newOffset = Math.min(intervalStart(), e.getOffset() + e.getNewLength()); if (!((DocumentEx)e.getDocument()).isInBulkUpdate() && e.isWholeTextReplaced()) { try { final int line = ((DocumentEventImpl)e).translateLineViaDiff(myLogicalCaret.line); newOffset = myEditor.logicalPositionToOffset(new LogicalPosition(line, myLogicalCaret.column)); } catch (FilesTooBigForDiffException ex) { LOG.info(ex); } } newOffset = DocumentUtil.alignToCodePointBoundary(getDocument(), newOffset); setIntervalStart(newOffset); setIntervalEnd(newOffset); } myLogicalColumnAdjustment = 0; myVisualColumnAdjustment = 0; if (oldOffset >= e.getOffset() && oldOffset <= e.getOffset() + e.getOldLength() && e.getNewLength() == 0 && e.getOldLength() > 0) { int inlaysToTheLeft = myEditor.getInlayModel().getInlineElementsInRange(e.getOffset(), e.getOffset()).size(); boolean hasInlaysToTheRight = myEditor.getInlayModel().hasInlineElementAt(e.getOffset() + e.getOldLength()); if (inlaysToTheLeft > 0 || hasInlaysToTheRight) { myLeansTowardsLargerOffsets = !hasInlaysToTheRight; myVisualColumnAdjustment = hasInlaysToTheRight ? inlaysToTheLeft : 0; } else if (oldOffset == e.getOffset()) { myLeansTowardsLargerOffsets = false; } } } private boolean needToShiftWhiteSpaces(final DocumentEvent e) { return e.getOffset() > 0 && Character.isWhitespace(e.getDocument().getImmutableCharSequence().charAt(e.getOffset() - 1)) && CharArrayUtil.containsOnlyWhiteSpaces(e.getNewFragment()) && !CharArrayUtil.containLineBreaks(e.getNewFragment()); } @Override protected void onReTarget(int startOffset, int endOffset, int destOffset) { int offset = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), offset)) { setIntervalStart(offset - 1); setIntervalEnd(offset - 1); } } } class SelectionMarker extends RangeMarkerImpl { // offsets of selection start/end position relative to end of line - can be non-zero in column selection mode // these are non-negative values, myStartVirtualOffset is always less or equal to myEndVirtualOffset private int startVirtualOffset; private int endVirtualOffset; private SelectionMarker(int start, int end) { super(myEditor.getDocument(), start, end, false); myEditor.getCaretModel().mySelectionMarkerTree.addInterval(this, start, end, false, false, false, 0); } private void resetVirtualSelection() { startVirtualOffset = 0; endVirtualOffset = 0; } private boolean hasVirtualSelection() { return endVirtualOffset > startVirtualOffset; } @Override public void dispose() { if (isValid()) { myEditor.getCaretModel().mySelectionMarkerTree.removeInterval(this); } } @Override protected void changedUpdateImpl(@NotNull DocumentEvent e) { super.changedUpdateImpl(e); if (isValid()) { int startOffset = intervalStart(); int endOffset = intervalEnd(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), startOffset)) setIntervalStart(startOffset - 1); if (DocumentUtil.isInsideSurrogatePair(getDocument(), endOffset)) setIntervalStart(endOffset - 1); } if (endVirtualOffset > 0 && isValid()) { Document document = e.getDocument(); int startAfter = intervalStart(); int endAfter = intervalEnd(); if (!DocumentUtil.isAtLineEnd(endAfter, document) || document.getLineNumber(startAfter) != document.getLineNumber(endAfter)) { resetVirtualSelection(); } } } @Override protected void onReTarget(int startOffset, int endOffset, int destOffset) { int start = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), start)) { setIntervalStart(start - 1); } int end = intervalEnd(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), end)) { setIntervalStart(end - 1); } } @Override public String toString() { return super.toString() + (hasVirtualSelection() ? " virtual selection: " + startVirtualOffset + "-" + endVirtualOffset : ""); } } }
platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.diagnostic.Dumpable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actions.EditorActionUtil; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.SelectionEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.editor.ex.FoldingModelEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.impl.event.DocumentEventImpl; import com.intellij.openapi.editor.impl.softwrap.SoftWrapHelper; import com.intellij.openapi.editor.impl.view.EditorPainter; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.DocumentUtil; import com.intellij.util.diff.FilesTooBigForDiffException; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.awt.*; import java.util.List; public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.CaretImpl"); private static final Key<CaretVisualAttributes> VISUAL_ATTRIBUTES_KEY = new Key<>("CaretAttributes"); private final EditorImpl myEditor; private boolean isValid = true; private LogicalPosition myLogicalCaret; private VerticalInfo myCaretInfo; private VisualPosition myVisibleCaret; private volatile PositionMarker myPositionMarker; private boolean myLeansTowardsLargerOffsets; private int myLogicalColumnAdjustment; int myVisualColumnAdjustment; private int myVisualLineStart; private int myVisualLineEnd; private boolean mySkipChangeRequests; /** * Initial horizontal caret position during vertical navigation. * Similar to {@link #myDesiredX}, but represents logical caret position ({@code getLogicalPosition().column}) rather than visual. */ private int myLastColumnNumber; private int myDesiredSelectionStartColumn = -1; private int myDesiredSelectionEndColumn = -1; /** * We check that caret is located at the target offset at the end of {@link #moveToOffset(int, boolean)} method. However, * it's possible that the following situation occurs: * <p/> * <pre> * <ol> * <li>Some client subscribes to caret change events;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} is called;</li> * <li>Caret position is changed during {@link #moveToLogicalPosition(LogicalPosition)} processing;</li> * <li>The client receives caret position change event and adjusts the position;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} processing is finished;</li> * <li>{@link #moveToLogicalPosition(LogicalPosition)} reports an error because the caret is not located at the target offset;</li> * </ol> * </pre> * <p/> * This field serves as a flag that reports unexpected caret position change requests nested from {@link #moveToOffset(int, boolean)}. */ private boolean myReportCaretMoves; /** * This field holds initial horizontal caret position during vertical navigation. It's used to determine target position when * moving to the new line. It is stored in pixels, not in columns, to account for non-monospaced fonts as well. * <p/> * Negative value means no coordinate should be preserved. */ private int myDesiredX = -1; private volatile SelectionMarker mySelectionMarker; private volatile VisualPosition myRangeMarkerStartPosition; private volatile VisualPosition myRangeMarkerEndPosition; private volatile boolean myRangeMarkerEndPositionIsLead; private boolean myUnknownDirection; private int myDocumentUpdateCounter; CaretImpl(EditorImpl editor) { myEditor = editor; myLogicalCaret = new LogicalPosition(0, 0); myVisibleCaret = new VisualPosition(0, 0); myCaretInfo = new VerticalInfo(0, 0); myPositionMarker = new PositionMarker(0); myVisualLineStart = 0; Document doc = myEditor.getDocument(); myVisualLineEnd = doc.getLineCount() > 1 ? doc.getLineStartOffset(1) : doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0); myDocumentUpdateCounter = editor.getCaretModel().myDocumentUpdateCounter; } @Override public void moveToOffset(int offset) { moveToOffset(offset, false); } @Override public void moveToOffset(final int offset, final boolean locateBeforeSoftWrap) { assertIsDispatchThread(); validateCallContext(); if (mySkipChangeRequests) { return; } myEditor.getCaretModel().doWithCaretMerging(() -> { LogicalPosition logicalPosition = myEditor.offsetToLogicalPosition(offset); CaretEvent event = moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, null, true, false); final LogicalPosition positionByOffsetAfterMove = myEditor.offsetToLogicalPosition(getOffset()); if (!positionByOffsetAfterMove.equals(logicalPosition)) { StringBuilder debugBuffer = new StringBuilder(); moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, debugBuffer, true, true); int actualOffset = getOffset(); int textStart = Math.max(0, Math.min(offset, actualOffset) - 1); final DocumentEx document = myEditor.getDocument(); int textEnd = Math.min(document.getTextLength() - 1, Math.max(offset, actualOffset) + 1); CharSequence text = document.getCharsSequence().subSequence(textStart, textEnd); int inverseOffset = myEditor.logicalPositionToOffset(logicalPosition); LOG.error( "caret moved to wrong offset. Please submit a dedicated ticket and attach current editor's text to it.", new Throwable(), AttachmentFactory.createContext( "Requested: offset=" + offset + ", logical position='" + logicalPosition + "' but actual: offset=" + actualOffset + ", logical position='" + myLogicalCaret + "' (" + positionByOffsetAfterMove + "). " + myEditor.dumpState() + "\ninterested text [" + textStart + ";" + textEnd + "): '" + text + "'\n debug trace: " + debugBuffer + "\nLogical position -> offset ('" + logicalPosition + "'->'" + inverseOffset + "')")); } if (event != null) { myEditor.getCaretModel().fireCaretPositionChanged(event); EditorActionUtil.selectNonexpandableFold(myEditor); } }); } @NotNull @Override public CaretModel getCaretModel() { return myEditor.getCaretModel(); } @Override public boolean isValid() { return isValid; } @Override public void moveCaretRelatively(final int _columnShift, final int lineShift, final boolean withSelection, final boolean scrollToCaret) { assertIsDispatchThread(); if (mySkipChangeRequests) { return; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request", new Throwable()); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling()) { CopyPasteManager.getInstance().stopKillRings(); } myEditor.getCaretModel().doWithCaretMerging(() -> { updateCachedStateIfNeeded(); int oldOffset = getOffset(); int columnShift = _columnShift; if (withSelection && lineShift == 0) { if (columnShift == -1) { int column; while ((column = myVisibleCaret.column + columnShift - (hasSelection() && oldOffset == getSelectionEnd() ? 1 : 0)) >= 0 && myEditor.getInlayModel().hasInlineElementAt(new VisualPosition(myVisibleCaret.line, column))) { columnShift--; } } else if (columnShift == 1) { while (myEditor.getInlayModel().hasInlineElementAt( new VisualPosition(myVisibleCaret.line, myVisibleCaret.column + columnShift - (hasSelection() && oldOffset == getSelectionStart() ? 0 : 1)))) { columnShift++; } } } final int leadSelectionOffset = getLeadSelectionOffset(); final VisualPosition leadSelectionPosition = getLeadSelectionPosition(); EditorSettings editorSettings = myEditor.getSettings(); VisualPosition visualCaret = getVisualPosition(); int lastColumnNumber = myLastColumnNumber; int desiredX = myDesiredX; if (columnShift == 0) { if (myDesiredX < 0) { desiredX = getCurrentX(); } } else { myDesiredX = desiredX = -1; } int newLineNumber = visualCaret.line + lineShift; int newColumnNumber = visualCaret.column + columnShift; boolean newLeansRight = lineShift == 0 && columnShift != 0 ? columnShift < 0 : visualCaret.leansRight; if (desiredX >= 0) { newColumnNumber = myEditor.xyToVisualPosition(new Point(desiredX, Math.max(0, newLineNumber) * myEditor.getLineHeight())).column; } Document document = myEditor.getDocument(); if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) { int lastLine = document.getLineCount() - 1; if (lastLine < 0) lastLine = 0; if (newColumnNumber > EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber) && newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) { newColumnNumber = 0; newLineNumber++; } } else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) { if (newColumnNumber < 0 && newLineNumber > 0) { newLineNumber--; newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); } } if (newColumnNumber < 0) newColumnNumber = 0; // There is a possible case that caret is located at the first line and user presses 'Shift+Up'. We want to select all text // from the document start to the current caret position then. So, we have a dedicated flag for tracking that. boolean selectToDocumentStart = false; if (newLineNumber < 0) { selectToDocumentStart = true; newLineNumber = 0; // We want to move caret to the first column if it's already located at the first line and 'Up' is pressed. newColumnNumber = 0; } VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber); if (!myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber, newLeansRight)); int offset = myEditor.logicalPositionToOffset(log); if (offset >= document.getTextLength() && columnShift == 0) { int lastOffsetColumn = myEditor.offsetToVisualPosition(document.getTextLength(), true, false).column; // We want to move caret to the last column if if it's located at the last line and 'Down' is pressed. if (lastOffsetColumn > newColumnNumber) { newColumnNumber = lastOffsetColumn; newLeansRight = true; } } if (!editorSettings.isCaretInsideTabs()) { CharSequence text = document.getCharsSequence(); if (offset >= 0 && offset < document.getTextLength()) { if (text.charAt(offset) == '\t' && (columnShift <= 0 || offset == oldOffset)) { if (columnShift <= 0) { newColumnNumber = myEditor.offsetToVisualPosition(offset, true, false).column; } else { SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset + 1); // There is a possible case that tabulation symbol is the last document symbol represented on a visual line before // soft wrap. We can't just use column from 'offset + 1' because it would point on a next visual line. if (softWrap == null) { newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column; } else { newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); } } } } } } pos = new VisualPosition(newLineNumber, newColumnNumber, newLeansRight); if (columnShift != 0 && lineShift == 0 && myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { LogicalPosition logical = myEditor.visualToLogicalPosition(pos); int softWrapOffset = myEditor.logicalPositionToOffset(logical); if (columnShift >= 0) { moveToOffset(softWrapOffset); } else { int line = myEditor.offsetToVisualLine(softWrapOffset - 1); moveToVisualPosition(new VisualPosition(line, EditorUtil.getLastVisualLineColumnNumber(myEditor, line))); } } else { moveToVisualPosition(pos); if (!editorSettings.isVirtualSpace() && columnShift == 0 && lastColumnNumber >=0) { setLastColumnNumber(lastColumnNumber); } } if (withSelection) { if (selectToDocumentStart) { setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(0), 0); } else if (pos.line >= myEditor.getVisibleLineCount()) { int endOffset = document.getTextLength(); if (leadSelectionOffset < endOffset) { setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(endOffset), endOffset); } } else { int selectionStartToUse = leadSelectionOffset; VisualPosition selectionStartPositionToUse = leadSelectionPosition; if (isUnknownDirection() || oldOffset > getSelectionStart() && oldOffset < getSelectionEnd()) { if (getOffset() > leadSelectionOffset ^ getSelectionStart() < getSelectionEnd()) { selectionStartToUse = getSelectionEnd(); selectionStartPositionToUse = getSelectionEndPosition(); } else { selectionStartToUse = getSelectionStart(); selectionStartPositionToUse = getSelectionStartPosition(); } } setSelection(selectionStartPositionToUse, selectionStartToUse, getVisualPosition(), getOffset()); } } else { removeSelection(); } if (scrollToCaret) { myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } if (desiredX >= 0) { myDesiredX = desiredX; } EditorActionUtil.selectNonexpandableFold(myEditor); }); } @Override public void moveToLogicalPosition(@NotNull final LogicalPosition pos) { myEditor.getCaretModel().doWithCaretMerging(() -> moveToLogicalPosition(pos, false, null, false, true)); } private CaretEvent doMoveToLogicalPosition(@NotNull LogicalPosition pos, boolean locateBeforeSoftWrap, @NonNls @Nullable StringBuilder debugBuffer, boolean adjustForInlays, boolean fireListeners) { assertIsDispatchThread(); updateCachedStateIfNeeded(); if (debugBuffer != null) { debugBuffer.append("Start moveToLogicalPosition(). Locate before soft wrap: ").append(locateBeforeSoftWrap).append(", position: ") .append(pos).append("\n"); } myDesiredX = -1; validateCallContext(); int column = pos.column; int line = pos.line; boolean leansForward = pos.leansForward; Document doc = myEditor.getDocument(); int lineCount = doc.getLineCount(); if (lineCount == 0) { if (debugBuffer != null) { debugBuffer.append("Resetting target logical line to zero as the document is empty\n"); } line = 0; } else if (line > lineCount - 1) { if (debugBuffer != null) { debugBuffer.append("Resetting target logical line (").append(line).append(") to ").append(lineCount - 1) .append(" as it is greater than total document lines number\n"); } line = lineCount - 1; } EditorSettings editorSettings = myEditor.getSettings(); if (!editorSettings.isVirtualSpace() && line < lineCount) { int lineEndOffset = doc.getLineEndOffset(line); final LogicalPosition endLinePosition = myEditor.offsetToLogicalPosition(lineEndOffset); int lineEndColumnNumber = endLinePosition.column; if (column > lineEndColumnNumber) { int oldColumn = column; column = lineEndColumnNumber; leansForward = true; if (debugBuffer != null) { debugBuffer.append("Resetting target logical column (").append(oldColumn).append(") to ").append(lineEndColumnNumber) .append(" because caret is not allowed to be located after line end (offset: ").append(lineEndOffset).append(", ") .append("logical position: ").append(endLinePosition).append(").\n"); } } } myEditor.getFoldingModel().flushCaretPosition(this); VerticalInfo oldInfo = myCaretInfo; LogicalPosition oldCaretPosition = myLogicalCaret; VisualPosition oldVisualPosition = myVisibleCaret; LogicalPosition logicalPositionToUse = new LogicalPosition(line, column, leansForward); final int offset = myEditor.logicalPositionToOffset(logicalPositionToUse); if (debugBuffer != null) { debugBuffer.append("Resulting logical position to use: ").append(logicalPositionToUse).append(". It's mapped to offset ").append(offset).append("\n"); } FoldRegion collapsedAt = myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset); if (collapsedAt != null && offset > collapsedAt.getStartOffset()) { if (debugBuffer != null) { debugBuffer.append("Scheduling expansion of fold region ").append(collapsedAt).append("\n"); } Runnable runnable = () -> { FoldRegion[] allCollapsedAt = myEditor.getFoldingModel().fetchCollapsedAt(offset); for (FoldRegion foldRange : allCollapsedAt) { foldRange.setExpanded(true); } }; mySkipChangeRequests = true; try { myEditor.getFoldingModel().runBatchFoldingOperation(runnable, false); } finally { mySkipChangeRequests = false; } } setCurrentLogicalCaret(logicalPositionToUse); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myVisibleCaret = myEditor.logicalToVisualPosition(myLogicalCaret); myVisualColumnAdjustment = 0; updateOffsetsFromLogicalPosition(); int newOffset = getOffset(); if (debugBuffer != null) { debugBuffer.append("Storing offset ").append(newOffset).append(" (mapped from logical position ").append(myLogicalCaret).append(")\n"); } if (adjustForInlays) { VisualPosition correctPosition = EditorUtil.inlayAwareOffsetToVisualPosition(myEditor, newOffset); assert correctPosition.line == myVisibleCaret.line; myVisualColumnAdjustment = correctPosition.column - myVisibleCaret.column; myVisibleCaret = correctPosition; } updateVisualLineInfo(); myEditor.updateCaretCursor(); requestRepaint(oldInfo); if (locateBeforeSoftWrap && SoftWrapHelper.isCaretAfterSoftWrap(this)) { int lineToUse = myVisibleCaret.line - 1; if (lineToUse >= 0) { final VisualPosition visualPosition = new VisualPosition(lineToUse, EditorUtil.getLastVisualLineColumnNumber(myEditor, lineToUse)); if (debugBuffer != null) { debugBuffer.append("Adjusting caret position by moving it before soft wrap. Moving to visual position ").append(visualPosition).append("\n"); } final LogicalPosition logicalPosition = myEditor.visualToLogicalPosition(visualPosition); final int tmpOffset = myEditor.logicalPositionToOffset(logicalPosition); if (tmpOffset == newOffset) { boolean restore = myReportCaretMoves; myReportCaretMoves = false; try { moveToVisualPosition(visualPosition); return null; } finally { myReportCaretMoves = restore; } } else { LOG.error("Invalid editor dimension mapping", new Throwable(), AttachmentFactory.createContext( "Expected to map visual position '" + visualPosition + "' to offset " + newOffset + " but got the following: -> logical position '" + logicalPosition + "'; -> offset " + tmpOffset + ". State: " + myEditor.dumpState())); } } } if (!oldVisualPosition.equals(myVisibleCaret) || !oldCaretPosition.equals(myLogicalCaret)) { CaretEvent event = new CaretEvent(myEditor, this, oldCaretPosition, myLogicalCaret); if (fireListeners) { myEditor.getCaretModel().fireCaretPositionChanged(event); } else { return event; } } return null; } private void updateOffsetsFromLogicalPosition() { int offset = myEditor.logicalPositionToOffset(myLogicalCaret); myPositionMarker = new PositionMarker(offset); myLeansTowardsLargerOffsets = myLogicalCaret.leansForward; myLogicalColumnAdjustment = myLogicalCaret.column - myEditor.offsetToLogicalPosition(offset).column; } private void setLastColumnNumber(int lastColumnNumber) { myLastColumnNumber = lastColumnNumber; } private void requestRepaint(VerticalInfo oldCaretInfo) { int lineHeight = myEditor.getLineHeight(); Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea(); final EditorGutterComponentEx gutter = myEditor.getGutterComponentEx(); final EditorComponentImpl content = myEditor.getContentComponent(); int updateWidth = myEditor.getScrollPane().getHorizontalScrollBar().getValue() + visibleArea.width; int additionalRepaintHeight = this == myEditor.getCaretModel().getPrimaryCaret() && Registry.is("editor.adjust.right.margin") && EditorPainter.isMarginShown(myEditor) ? 1 : 0; if (Math.abs(myCaretInfo.y - oldCaretInfo.y) <= 2 * lineHeight) { int minY = Math.min(oldCaretInfo.y, myCaretInfo.y); int maxY = Math.max(oldCaretInfo.y + oldCaretInfo.height, myCaretInfo.y + myCaretInfo.height); content.repaintEditorComponent(0, minY - additionalRepaintHeight, updateWidth, maxY - minY + additionalRepaintHeight); gutter.repaint(0, minY, gutter.getWidth(), maxY - minY); } else { content.repaintEditorComponent(0, oldCaretInfo.y - additionalRepaintHeight, updateWidth, oldCaretInfo.height + lineHeight + additionalRepaintHeight); gutter.repaint(0, oldCaretInfo.y, updateWidth, oldCaretInfo.height + lineHeight); content.repaintEditorComponent(0, myCaretInfo.y - additionalRepaintHeight, updateWidth, myCaretInfo.height + lineHeight + additionalRepaintHeight); gutter.repaint(0, myCaretInfo.y, updateWidth, myCaretInfo.height + lineHeight); } } @Override public void moveToVisualPosition(@NotNull final VisualPosition pos) { myEditor.getCaretModel().doWithCaretMerging(() -> moveToVisualPosition(pos, true)); } void moveToVisualPosition(@NotNull VisualPosition pos, boolean fireListeners) { assertIsDispatchThread(); validateCallContext(); if (mySkipChangeRequests) { return; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request"); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling() && !pos.equals(myVisibleCaret)) { CopyPasteManager.getInstance().stopKillRings(); } updateCachedStateIfNeeded(); myDesiredX = -1; int column = pos.column; int line = pos.line; boolean leanRight = pos.leansRight; int lastLine = myEditor.getVisibleLineCount() - 1; if (lastLine <= 0) { lastLine = 0; } if (line > lastLine) { line = lastLine; } EditorSettings editorSettings = myEditor.getSettings(); if (!editorSettings.isVirtualSpace()) { int lineEndColumn = EditorUtil.getLastVisualLineColumnNumber(myEditor, line); if (column > lineEndColumn && !myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { column = lineEndColumn; leanRight = true; } } VisualPosition oldVisualPosition = myVisibleCaret; myVisibleCaret = new VisualPosition(line, column, leanRight); VerticalInfo oldInfo = myCaretInfo; LogicalPosition oldPosition = myLogicalCaret; setCurrentLogicalCaret(myEditor.visualToLogicalPosition(myVisibleCaret)); VisualPosition mappedPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisualColumnAdjustment = mappedPosition.line == myVisibleCaret.line && myVisibleCaret.column > mappedPosition.column && !myLogicalCaret.leansForward ? myVisibleCaret.column - mappedPosition.column : 0; updateOffsetsFromLogicalPosition(); updateVisualLineInfo(); myEditor.getFoldingModel().flushCaretPosition(this); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myEditor.updateCaretCursor(); requestRepaint(oldInfo); if (fireListeners && (!oldPosition.equals(myLogicalCaret) || !oldVisualPosition.equals(myVisibleCaret))) { CaretEvent event = new CaretEvent(myEditor, this, oldPosition, myLogicalCaret); myEditor.getCaretModel().fireCaretPositionChanged(event); } } @Nullable CaretEvent moveToLogicalPosition(@NotNull LogicalPosition pos, boolean locateBeforeSoftWrap, @Nullable StringBuilder debugBuffer, boolean adjustForInlays, boolean fireListeners) { if (mySkipChangeRequests) { return null; } if (myReportCaretMoves) { LOG.error("Unexpected caret move request"); } if (!myEditor.isStickySelection() && !myEditor.getDocument().isInEventsHandling() && !pos.equals(myLogicalCaret)) { CopyPasteManager.getInstance().stopKillRings(); } myReportCaretMoves = true; try { return doMoveToLogicalPosition(pos, locateBeforeSoftWrap, debugBuffer, adjustForInlays, fireListeners); } finally { myReportCaretMoves = false; } } private static void assertIsDispatchThread() { EditorImpl.assertIsDispatchThread(); } private void validateCallContext() { LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread() || !myEditor.getCaretModel().myIsInUpdate, "Caret model is in its update process. All requests are illegal at this point."); } @Override public void dispose() { if (myPositionMarker != null) { myPositionMarker = null; } if (mySelectionMarker != null) { mySelectionMarker = null; } isValid = false; } @Override public boolean isUpToDate() { return !myEditor.getCaretModel().myIsInUpdate && !myReportCaretMoves; } @NotNull @Override public LogicalPosition getLogicalPosition() { validateCallContext(); updateCachedStateIfNeeded(); return myLogicalCaret; } @NotNull @Override public VisualPosition getVisualPosition() { validateCallContext(); updateCachedStateIfNeeded(); return myVisibleCaret; } @Override public int getOffset() { validateCallContext(); validateContext(false); PositionMarker marker = myPositionMarker; if (marker == null) return 0; // caret was disposed assert marker.isValid(); return marker.getStartOffset(); } @Override public int getVisualLineStart() { updateCachedStateIfNeeded(); return myVisualLineStart; } @Override public int getVisualLineEnd() { updateCachedStateIfNeeded(); return myVisualLineEnd; } @NotNull private VerticalInfo createVerticalInfo(LogicalPosition position) { Document document = myEditor.getDocument(); int logicalLine = position.line; if (logicalLine >= document.getLineCount()) { logicalLine = Math.max(0, document.getLineCount() - 1); } int startOffset = document.getLineStartOffset(logicalLine); int endOffset = document.getLineEndOffset(logicalLine); // There is a possible case that active logical line is represented on multiple lines due to soft wraps processing. // We want to highlight those visual lines as 'active' then, so, we calculate 'y' position for the logical line start // and height in accordance with the number of occupied visual lines. int visualLine = myEditor.offsetToVisualLine(document.getLineStartOffset(logicalLine)); int y = myEditor.visibleLineToY(visualLine); int lineHeight = myEditor.getLineHeight(); int height = lineHeight; List<? extends SoftWrap> softWraps = myEditor.getSoftWrapModel().getSoftWrapsForRange(startOffset, endOffset); for (SoftWrap softWrap : softWraps) { height += StringUtil.countNewLines(softWrap.getText()) * lineHeight; } return new VerticalInfo(y, height); } /** * Recalculates caret visual position without changing its logical position (called when soft wraps are changing) */ void updateVisualPosition() { updateCachedStateIfNeeded(); VerticalInfo oldInfo = myCaretInfo; LogicalPosition visUnawarePos = new LogicalPosition(myLogicalCaret.line, myLogicalCaret.column, myLogicalCaret.leansForward); setCurrentLogicalCaret(visUnawarePos); VisualPosition visualPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisibleCaret = new VisualPosition(visualPosition.line, visualPosition.column + myVisualColumnAdjustment, visualPosition.leansRight); updateVisualLineInfo(); myEditor.updateCaretCursor(); requestRepaint(oldInfo); } private void updateVisualLineInfo() { myVisualLineStart = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0))); myVisualLineEnd = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0))); } void onInlayAdded(int offset) { updateCachedStateIfNeeded(); int currentOffset = getOffset(); if (offset == currentOffset) { VisualPosition pos = EditorUtil.inlayAwareOffsetToVisualPosition(myEditor, offset); moveToVisualPosition(pos); } else { updateVisualPosition(); } } void onInlayRemoved(int offset, int order) { int currentOffset = getOffset(); if (offset == currentOffset && myVisualColumnAdjustment > 0 && myVisualColumnAdjustment > order) myVisualColumnAdjustment--; updateVisualPosition(); } private void setCurrentLogicalCaret(@NotNull LogicalPosition position) { myLogicalCaret = position; myCaretInfo = createVerticalInfo(position); } int getWordAtCaretStart() { Document document = myEditor.getDocument(); int offset = getOffset(); if (offset == 0) return 0; int lineNumber = getLogicalPosition().line; int newOffset = offset - 1; int minOffset = lineNumber > 0 ? document.getLineEndOffset(lineNumber - 1) : 0; boolean camel = myEditor.getSettings().isCamelWords(); for (; newOffset > minOffset; newOffset--) { if (EditorActionUtil.isWordOrLexemeStart(myEditor, newOffset, camel)) break; } return newOffset; } int getWordAtCaretEnd() { Document document = myEditor.getDocument(); int offset = getOffset(); if (offset >= document.getTextLength() - 1 || document.getLineCount() == 0) return offset; int newOffset = offset + 1; int lineNumber = getLogicalPosition().line; int maxOffset = document.getLineEndOffset(lineNumber); if (newOffset > maxOffset) { if (lineNumber + 1 >= document.getLineCount()) return offset; maxOffset = document.getLineEndOffset(lineNumber + 1); } boolean camel = myEditor.getSettings().isCamelWords(); for (; newOffset < maxOffset; newOffset++) { if (EditorActionUtil.isWordOrLexemeEnd(myEditor, newOffset, camel)) break; } return newOffset; } private CaretImpl cloneWithoutSelection() { updateCachedStateIfNeeded(); CaretImpl clone = new CaretImpl(myEditor); clone.myLogicalCaret = myLogicalCaret; clone.myCaretInfo = myCaretInfo; clone.myVisibleCaret = myVisibleCaret; clone.myPositionMarker = new PositionMarker(getOffset()); clone.myLeansTowardsLargerOffsets = myLeansTowardsLargerOffsets; clone.myLogicalColumnAdjustment = myLogicalColumnAdjustment; clone.myVisualColumnAdjustment = myVisualColumnAdjustment; clone.myVisualLineStart = myVisualLineStart; clone.myVisualLineEnd = myVisualLineEnd; clone.mySkipChangeRequests = mySkipChangeRequests; clone.myLastColumnNumber = myLastColumnNumber; clone.myReportCaretMoves = myReportCaretMoves; clone.myDesiredX = myDesiredX; clone.myDesiredSelectionStartColumn = -1; clone.myDesiredSelectionEndColumn = -1; return clone; } @Nullable @Override public Caret clone(boolean above) { assertIsDispatchThread(); int lineShift = above ? -1 : 1; LogicalPosition oldPosition = getLogicalPosition(); int newLine = oldPosition.line + lineShift; if (newLine < 0 || newLine >= myEditor.getDocument().getLineCount()) { return null; } final CaretImpl clone = cloneWithoutSelection(); final int newSelectionStartOffset; final int newSelectionEndOffset; final int newSelectionStartColumn; final int newSelectionEndColumn; final VisualPosition newSelectionStartPosition; final VisualPosition newSelectionEndPosition; final boolean hasNewSelection; if (hasSelection() || myDesiredSelectionStartColumn >=0 || myDesiredSelectionEndColumn >= 0) { VisualPosition startPosition = getSelectionStartPosition(); VisualPosition endPosition = getSelectionEndPosition(); VisualPosition leadPosition = getLeadSelectionPosition(); boolean leadIsStart = leadPosition.equals(startPosition); boolean leadIsEnd = leadPosition.equals(endPosition); LogicalPosition selectionStart = myEditor.visualToLogicalPosition(leadIsStart || leadIsEnd ? leadPosition : startPosition); LogicalPosition selectionEnd = myEditor.visualToLogicalPosition(leadIsEnd ? startPosition : endPosition); newSelectionStartColumn = myDesiredSelectionStartColumn < 0 ? selectionStart.column : myDesiredSelectionStartColumn; newSelectionEndColumn = myDesiredSelectionEndColumn < 0 ? selectionEnd.column : myDesiredSelectionEndColumn; LogicalPosition newSelectionStart = truncate(selectionStart.line + lineShift, newSelectionStartColumn); LogicalPosition newSelectionEnd = truncate(selectionEnd.line + lineShift, newSelectionEndColumn); newSelectionStartOffset = myEditor.logicalPositionToOffset(newSelectionStart); newSelectionEndOffset = myEditor.logicalPositionToOffset(newSelectionEnd); newSelectionStartPosition = myEditor.logicalToVisualPosition(newSelectionStart); newSelectionEndPosition = myEditor.logicalToVisualPosition(newSelectionEnd); hasNewSelection = !newSelectionStart.equals(newSelectionEnd); } else { newSelectionStartOffset = 0; newSelectionEndOffset = 0; newSelectionStartPosition = null; newSelectionEndPosition = null; hasNewSelection = false; newSelectionStartColumn = -1; newSelectionEndColumn = -1; } clone.moveToLogicalPosition(new LogicalPosition(newLine, myLastColumnNumber), false, null, false, false); clone.myLastColumnNumber = myLastColumnNumber; clone.myDesiredX = myDesiredX >= 0 ? myDesiredX : getCurrentX(); clone.myDesiredSelectionStartColumn = newSelectionStartColumn; clone.myDesiredSelectionEndColumn = newSelectionEndColumn; if (myEditor.getCaretModel().addCaret(clone, true)) { if (hasNewSelection) { myEditor.getCaretModel().doWithCaretMerging( () -> clone.setSelection(newSelectionStartPosition, newSelectionStartOffset, newSelectionEndPosition, newSelectionEndOffset)); if (!clone.isValid()) { return null; } } myEditor.getScrollingModel().scrollTo(clone.getLogicalPosition(), ScrollType.RELATIVE); return clone; } else { Disposer.dispose(clone); return null; } } private LogicalPosition truncate(int line, int column) { if (line < 0) { return new LogicalPosition(0, 0); } else if (line >= myEditor.getDocument().getLineCount()) { return myEditor.offsetToLogicalPosition(myEditor.getDocument().getTextLength()); } else { return new LogicalPosition(line, column); } } /** * @return information on whether current selection's direction in known * @see #setUnknownDirection(boolean) */ boolean isUnknownDirection() { return myUnknownDirection; } /** * There is a possible case that we don't know selection's direction. For example, a user might triple-click editor (select the * whole line). We can't say what selection end is a {@link #getLeadSelectionOffset() leading end} then. However, that matters * in a situation when a user clicks before or after that line holding Shift key. It's expected that the selection is expanded * up to that point than. * <p/> * That's why we allow to specify that the direction is unknown and {@link #isUnknownDirection() expose this information} * later. * <p/> * <b>Note:</b> when this method is called with {@code 'true'}, subsequent calls are guaranteed to return {@code true} * until selection is changed. 'Unknown direction' flag is automatically reset then. * */ void setUnknownDirection(boolean unknownDirection) { myUnknownDirection = unknownDirection; } @Override public int getSelectionStart() { validateContext(false); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null) { return marker.getStartOffset(); } } return getOffset(); } @NotNull @Override public VisualPosition getSelectionStartPosition() { validateContext(true); VisualPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { position = getRangeMarkerStartPosition(); if (position == null) { VisualPosition startPosition = myEditor.offsetToVisualPosition(marker.getStartOffset(), true, false); VisualPosition endPosition = myEditor.offsetToVisualPosition(marker.getEndOffset(), false, true); position = startPosition.after(endPosition) ? endPosition : startPosition; } } else { position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset(), getLogicalPosition().leansForward, false); } if (hasVirtualSelection()) { position = new VisualPosition(position.line, position.column + marker.startVirtualOffset); } return position; } LogicalPosition getSelectionStartLogicalPosition() { validateContext(true); LogicalPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { VisualPosition visualPosition = getRangeMarkerStartPosition(); position = visualPosition == null ? myEditor.offsetToLogicalPosition(marker.getStartOffset()).leanForward(true) : myEditor.visualToLogicalPosition(visualPosition); } else { position = getLogicalPosition(); } if (hasVirtualSelection()) { position = new LogicalPosition(position.line, position.column + marker.startVirtualOffset); } return position; } @Override public int getSelectionEnd() { validateContext(false); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null) { return marker.getEndOffset(); } } return getOffset(); } @NotNull @Override public VisualPosition getSelectionEndPosition() { validateContext(true); VisualPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { position = getRangeMarkerEndPosition(); if (position == null) { VisualPosition startPosition = myEditor.offsetToVisualPosition(marker.getStartOffset(), true, false); VisualPosition endPosition = myEditor.offsetToVisualPosition(marker.getEndOffset(), false, true); position = startPosition.after(endPosition) ? startPosition : endPosition; } } else { position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset(), getLogicalPosition().leansForward, false); } if (hasVirtualSelection()) { position = new VisualPosition(position.line, position.column + marker.endVirtualOffset); } return position; } LogicalPosition getSelectionEndLogicalPosition() { validateContext(true); LogicalPosition position; SelectionMarker marker = mySelectionMarker; if (hasSelection()) { VisualPosition visualPosition = getRangeMarkerEndPosition(); position = visualPosition == null ? myEditor.offsetToLogicalPosition(marker.getEndOffset()) : myEditor.visualToLogicalPosition(visualPosition); } else { position = getLogicalPosition(); } if (hasVirtualSelection()) { position = new LogicalPosition(position.line, position.column + marker.endVirtualOffset); } return position; } @Override public boolean hasSelection() { validateContext(false); SelectionMarker marker = mySelectionMarker; return marker != null && marker.isValid() && (marker.getEndOffset() > marker.getStartOffset() || isVirtualSelectionEnabled() && marker.hasVirtualSelection()); } @Override public void setSelection(int startOffset, int endOffset) { setSelection(startOffset, endOffset, true); } @Override public void setSelection(int startOffset, int endOffset, boolean updateSystemSelection) { doSetSelection(myEditor.offsetToVisualPosition(startOffset, true, false), startOffset, myEditor.offsetToVisualPosition(endOffset, false, true), endOffset, false, updateSystemSelection, true); } @Override public void setSelection(int startOffset, @Nullable VisualPosition endPosition, int endOffset) { VisualPosition startPosition; if (hasSelection()) { startPosition = getLeadSelectionPosition(); } else { startPosition = myEditor.offsetToVisualPosition(startOffset, true, false); } setSelection(startPosition, startOffset, endPosition, endOffset); } @Override public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset) { setSelection(startPosition, startOffset, endPosition, endOffset, true); } @Override public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset, boolean updateSystemSelection) { VisualPosition startPositionToUse = startPosition == null ? myEditor.offsetToVisualPosition(startOffset, true, false) : startPosition; VisualPosition endPositionToUse = endPosition == null ? myEditor.offsetToVisualPosition(endOffset, false, true) : endPosition; doSetSelection(startPositionToUse, startOffset, endPositionToUse, endOffset, true, updateSystemSelection, true); } void doSetSelection(@NotNull final VisualPosition startPosition, final int _startOffset, @NotNull final VisualPosition endPosition, final int _endOffset, final boolean visualPositionAware, final boolean updateSystemSelection, final boolean fireListeners) { myEditor.getCaretModel().doWithCaretMerging(() -> { int startOffset = DocumentUtil.alignToCodePointBoundary(myEditor.getDocument(), _startOffset); int endOffset = DocumentUtil.alignToCodePointBoundary(myEditor.getDocument(), _endOffset); myUnknownDirection = false; final Document doc = myEditor.getDocument(); validateContext(true); int textLength = doc.getTextLength(); if (startOffset < 0 || startOffset > textLength) { LOG.error("Wrong startOffset: " + startOffset + ", textLength=" + textLength); } if (endOffset < 0 || endOffset > textLength) { LOG.error("Wrong endOffset: " + endOffset + ", textLength=" + textLength); } if (!visualPositionAware && startOffset == endOffset) { removeSelection(); return; } /* Normalize selection */ boolean switchedOffsets = false; if (startOffset > endOffset) { int tmp = startOffset; startOffset = endOffset; endOffset = tmp; switchedOffsets = true; } FoldingModelEx foldingModel = myEditor.getFoldingModel(); FoldRegion startFold = foldingModel.getCollapsedRegionAtOffset(startOffset); if (startFold != null && startFold.getStartOffset() < startOffset) { startOffset = startFold.getStartOffset(); } FoldRegion endFold = foldingModel.getCollapsedRegionAtOffset(endOffset); if (endFold != null && endFold.getStartOffset() < endOffset) { // All visual positions that lay at collapsed fold region placeholder are mapped to the same offset. Hence, there are // at least two distinct situations - selection end is located inside collapsed fold region placeholder and just before it. // We want to expand selection to the fold region end at the former case and keep selection as-is at the latest one. endOffset = endFold.getEndOffset(); } int oldSelectionStart; int oldSelectionEnd; if (hasSelection()) { oldSelectionStart = getSelectionStart(); oldSelectionEnd = getSelectionEnd(); if (oldSelectionStart == startOffset && oldSelectionEnd == endOffset && !visualPositionAware) return; } else { oldSelectionStart = oldSelectionEnd = getOffset(); } SelectionMarker marker = new SelectionMarker(startOffset, endOffset); if (visualPositionAware) { if (endPosition.after(startPosition)) { setRangeMarkerStartPosition(startPosition); setRangeMarkerEndPosition(endPosition); setRangeMarkerEndPositionIsLead(false); } else { setRangeMarkerStartPosition(endPosition); setRangeMarkerEndPosition(startPosition); setRangeMarkerEndPositionIsLead(true); } if (isVirtualSelectionEnabled() && myEditor.getDocument().getLineNumber(startOffset) == myEditor.getDocument().getLineNumber(endOffset)) { int endLineColumn = myEditor.offsetToVisualPosition(endOffset).column; int startDiff = EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? endOffset : startOffset) ? startPosition.column - endLineColumn : 0; int endDiff = EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? startOffset : endOffset) ? endPosition.column - endLineColumn : 0; marker.startVirtualOffset = Math.max(0, Math.min(startDiff, endDiff)); marker.endVirtualOffset = Math.max(0, Math.max(startDiff, endDiff)); } } mySelectionMarker = marker; if (fireListeners) { myEditor.getSelectionModel().fireSelectionChanged(new SelectionEvent(myEditor, oldSelectionStart, oldSelectionEnd, startOffset, endOffset)); } if (updateSystemSelection) { myEditor.getCaretModel().updateSystemSelection(); } }); } @Override public void removeSelection() { if (myEditor.isStickySelection()) { // Most of our 'change caret position' actions (like move caret to word start/end etc) remove active selection. // However, we don't want to do that for 'sticky selection'. return; } myEditor.getCaretModel().doWithCaretMerging(() -> { validateContext(true); int caretOffset = getOffset(); RangeMarker marker = mySelectionMarker; if (marker != null && marker.isValid()) { int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); mySelectionMarker = null; myEditor.getSelectionModel().fireSelectionChanged(new SelectionEvent(myEditor, startOffset, endOffset, caretOffset, caretOffset)); } }); } @Override public int getLeadSelectionOffset() { validateContext(false); int caretOffset = getOffset(); if (hasSelection()) { RangeMarker marker = mySelectionMarker; if (marker != null && marker.isValid()) { int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); if (caretOffset != startOffset && caretOffset != endOffset) { // Try to check if current selection is tweaked by fold region. FoldingModelEx foldingModel = myEditor.getFoldingModel(); FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(caretOffset); if (foldRegion != null) { if (foldRegion.getStartOffset() == startOffset) { return endOffset; } else if (foldRegion.getEndOffset() == endOffset) { return startOffset; } } } if (caretOffset == endOffset) { return startOffset; } else { return endOffset; } } } return caretOffset; } @NotNull @Override public VisualPosition getLeadSelectionPosition() { SelectionMarker marker = mySelectionMarker; VisualPosition caretPosition = getVisualPosition(); if (isVirtualSelectionEnabled() && !hasSelection()) { return caretPosition; } if (marker == null || !marker.isValid()) { return caretPosition; } if (isRangeMarkerEndPositionIsLead()) { VisualPosition result = getRangeMarkerEndPosition(); if (result == null) { return getSelectionEndPosition(); } else { if (hasVirtualSelection()) { result = new VisualPosition(result.line, result.column + marker.endVirtualOffset); } return result; } } else { VisualPosition result = getRangeMarkerStartPosition(); if (result == null) { return getSelectionStartPosition(); } else { if (hasVirtualSelection()) { result = new VisualPosition(result.line, result.column + marker.startVirtualOffset); } return result; } } } @Override public void selectLineAtCaret() { validateContext(true); myEditor.getCaretModel().doWithCaretMerging(() -> SelectionModelImpl.doSelectLineAtCaret(this)); } @Override public void selectWordAtCaret(final boolean honorCamelWordsSettings) { validateContext(true); myEditor.getCaretModel().doWithCaretMerging(() -> { removeSelection(); final EditorSettings settings = myEditor.getSettings(); boolean camelTemp = settings.isCamelWords(); final boolean needOverrideSetting = camelTemp && !honorCamelWordsSettings; if (needOverrideSetting) { settings.setCamelWords(false); } try { EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); handler.execute(myEditor, this, myEditor.getDataContext()); } finally { if (needOverrideSetting) { settings.resetCamelWords(); } } }); } @Nullable @Override public String getSelectedText() { if (!hasSelection()) { return null; } SelectionMarker selectionMarker = mySelectionMarker; CharSequence text = myEditor.getDocument().getCharsSequence(); int selectionStart = getSelectionStart(); int selectionEnd = getSelectionEnd(); String selectedText = text.subSequence(selectionStart, selectionEnd).toString(); if (isVirtualSelectionEnabled() && selectionMarker.hasVirtualSelection()) { int padding = selectionMarker.endVirtualOffset - selectionMarker.startVirtualOffset; StringBuilder builder = new StringBuilder(selectedText.length() + padding); builder.append(selectedText); for (int i = 0; i < padding; i++) { builder.append(' '); } return builder.toString(); } else { return selectedText; } } private static void validateContext(boolean requireEdt) { if (requireEdt) { ApplicationManager.getApplication().assertIsDispatchThread(); } else { ApplicationManager.getApplication().assertReadAccessAllowed(); } } private boolean isVirtualSelectionEnabled() { return myEditor.isColumnMode(); } boolean hasVirtualSelection() { validateContext(false); SelectionMarker marker = mySelectionMarker; return marker != null && marker.isValid() && isVirtualSelectionEnabled() && marker.hasVirtualSelection(); } void resetVirtualSelection() { SelectionMarker marker = mySelectionMarker; if (marker != null) marker.resetVirtualSelection(); } private int getCurrentX() { return myEditor.visualPositionToXY(myVisibleCaret).x; } @Override @NotNull public EditorImpl getEditor() { return myEditor; } @Override public String toString() { return "Caret at " + (myDocumentUpdateCounter == myEditor.getCaretModel().myDocumentUpdateCounter ? myVisibleCaret : getOffset()) + (mySelectionMarker == null ? "" : ", selection marker: " + mySelectionMarker); } @Override public boolean isAtRtlLocation() { return myEditor.myView.isRtlLocation(getVisualPosition()); } @Override public boolean isAtBidiRunBoundary() { return myEditor.myView.isAtBidiRunBoundary(getVisualPosition()); } @NotNull @Override public CaretVisualAttributes getVisualAttributes() { CaretVisualAttributes attrs = getUserData(VISUAL_ATTRIBUTES_KEY); return attrs == null ? CaretVisualAttributes.DEFAULT : attrs; } @Override public void setVisualAttributes(@NotNull CaretVisualAttributes attributes) { putUserData(VISUAL_ATTRIBUTES_KEY, attributes == CaretVisualAttributes.DEFAULT ? null : attributes); requestRepaint(myCaretInfo); } @NotNull @Override public String dumpState() { return "{valid: " + isValid + ", update counter: " + myDocumentUpdateCounter + ", position: " + myPositionMarker + ", logical pos: " + myLogicalCaret + ", visual pos: " + myVisibleCaret + ", visual line start: " + myVisualLineStart + ", visual line end: " + myVisualLineEnd + ", skip change requests: " + mySkipChangeRequests + ", desired selection start column: " + myDesiredSelectionStartColumn + ", desired selection end column: " + myDesiredSelectionEndColumn + ", report caret moves: " + myReportCaretMoves + ", desired x: " + myDesiredX + ", selection marker: " + mySelectionMarker + ", rangeMarker start position: " + myRangeMarkerStartPosition + ", rangeMarker end position: " + myRangeMarkerEndPosition + ", rangeMarker end position is lead: " + myRangeMarkerEndPositionIsLead + ", unknown direction: " + myUnknownDirection + ", logical column adjustment: " + myLogicalColumnAdjustment + ", visual column adjustment: " + myVisualColumnAdjustment + '}'; } /** * Encapsulates information about target vertical range info - its {@code 'y'} coordinate and height in pixels. */ private static class VerticalInfo { public final int y; public final int height; private VerticalInfo(int y, int height) { this.y = y; this.height = height; } } @Nullable private VisualPosition getRangeMarkerStartPosition() { invalidateRangeMarkerVisualPositions(mySelectionMarker); return myRangeMarkerStartPosition; } private void setRangeMarkerStartPosition(@NotNull VisualPosition startPosition) { myRangeMarkerStartPosition = startPosition; } @Nullable private VisualPosition getRangeMarkerEndPosition() { invalidateRangeMarkerVisualPositions(mySelectionMarker); return myRangeMarkerEndPosition; } private void setRangeMarkerEndPosition(@NotNull VisualPosition endPosition) { myRangeMarkerEndPosition = endPosition; } private boolean isRangeMarkerEndPositionIsLead() { return myRangeMarkerEndPositionIsLead; } private void setRangeMarkerEndPositionIsLead(boolean endPositionIsLead) { myRangeMarkerEndPositionIsLead = endPositionIsLead; } private void invalidateRangeMarkerVisualPositions(RangeMarker marker) { SoftWrapModelImpl model = myEditor.getSoftWrapModel(); InlayModelImpl inlayModel = myEditor.getInlayModel(); int startOffset = marker.getStartOffset(); int endOffset = marker.getEndOffset(); if ((myRangeMarkerStartPosition == null || !myEditor.offsetToVisualPosition(startOffset, true, false).equals(myRangeMarkerStartPosition)) && model.getSoftWrap(startOffset) == null && !inlayModel.hasInlineElementAt(startOffset) || (myRangeMarkerEndPosition == null || !myEditor.offsetToVisualPosition(endOffset, false, true).equals(myRangeMarkerEndPosition)) && model.getSoftWrap(endOffset) == null && !inlayModel.hasInlineElementAt(endOffset)) { myRangeMarkerStartPosition = null; myRangeMarkerEndPosition = null; } } void updateCachedStateIfNeeded() { if (!ApplicationManager.getApplication().isDispatchThread()) return; int modelCounter = myEditor.getCaretModel().myDocumentUpdateCounter; if (myDocumentUpdateCounter != modelCounter) { LogicalPosition lp = myEditor.offsetToLogicalPosition(getOffset()); setCurrentLogicalCaret(new LogicalPosition(lp.line, lp.column + myLogicalColumnAdjustment, myLeansTowardsLargerOffsets)); VisualPosition visualPosition = myEditor.logicalToVisualPosition(myLogicalCaret); myVisibleCaret = new VisualPosition(visualPosition.line, visualPosition.column + myVisualColumnAdjustment, visualPosition.leansRight); updateVisualLineInfo(); setLastColumnNumber(myLogicalCaret.column); myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1; myDesiredX = -1; myDocumentUpdateCounter = modelCounter; } } @TestOnly public void validateState() { LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getOffset())); LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getSelectionStart())); LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(myEditor.getDocument(), getSelectionEnd())); } class PositionMarker extends RangeMarkerImpl { private PositionMarker(int offset) { super(myEditor.getDocument(), offset, offset, false); myEditor.getCaretModel().myPositionMarkerTree.addInterval(this, offset, offset, false, false, false, 0); } @Override public void dispose() { if (isValid()) { myEditor.getCaretModel().myPositionMarkerTree.removeInterval(this); } } @Override protected void changedUpdateImpl(@NotNull DocumentEvent e) { int oldOffset = intervalStart(); super.changedUpdateImpl(e); if (isValid()) { // Under certain conditions, when text is inserted at caret position, we position caret at the end of inserted text. // Ideally, client code should be responsible for positioning caret after document modification, but in case of // postponed formatting (after PSI modifications), this is hard to implement, so a heuristic below is used. if (e.getOldLength() == 0 && oldOffset == e.getOffset() && !Boolean.TRUE.equals(myEditor.getUserData(EditorImpl.DISABLE_CARET_SHIFT_ON_WHITESPACE_INSERTION)) && needToShiftWhiteSpaces(e)) { int afterInserted = e.getOffset() + e.getNewLength(); setIntervalStart(afterInserted); setIntervalEnd(afterInserted); } int offset = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), offset)) { setIntervalStart(offset - 1); setIntervalEnd(offset - 1); } } else { setValid(true); int newOffset = Math.min(intervalStart(), e.getOffset() + e.getNewLength()); if (!((DocumentEx)e.getDocument()).isInBulkUpdate() && e.isWholeTextReplaced()) { try { final int line = ((DocumentEventImpl)e).translateLineViaDiff(myLogicalCaret.line); newOffset = myEditor.logicalPositionToOffset(new LogicalPosition(line, myLogicalCaret.column)); } catch (FilesTooBigForDiffException ex) { LOG.info(ex); } } newOffset = DocumentUtil.alignToCodePointBoundary(getDocument(), newOffset); setIntervalStart(newOffset); setIntervalEnd(newOffset); } myLogicalColumnAdjustment = 0; myVisualColumnAdjustment = 0; if (oldOffset >= e.getOffset() && oldOffset <= e.getOffset() + e.getOldLength() && e.getNewLength() == 0 && e.getOldLength() > 0) { int inlaysToTheLeft = myEditor.getInlayModel().getInlineElementsInRange(e.getOffset(), e.getOffset()).size(); boolean hasInlaysToTheRight = myEditor.getInlayModel().hasInlineElementAt(e.getOffset() + e.getOldLength()); if (inlaysToTheLeft > 0 || hasInlaysToTheRight) { myLeansTowardsLargerOffsets = !hasInlaysToTheRight; myVisualColumnAdjustment = hasInlaysToTheRight ? inlaysToTheLeft : 0; } else if (oldOffset == e.getOffset()) { myLeansTowardsLargerOffsets = false; } } } private boolean needToShiftWhiteSpaces(final DocumentEvent e) { return e.getOffset() > 0 && Character.isWhitespace(e.getDocument().getImmutableCharSequence().charAt(e.getOffset() - 1)) && CharArrayUtil.containsOnlyWhiteSpaces(e.getNewFragment()) && !CharArrayUtil.containLineBreaks(e.getNewFragment()); } @Override protected void onReTarget(int startOffset, int endOffset, int destOffset) { int offset = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), offset)) { setIntervalStart(offset - 1); setIntervalEnd(offset - 1); } } } class SelectionMarker extends RangeMarkerImpl { // offsets of selection start/end position relative to end of line - can be non-zero in column selection mode // these are non-negative values, myStartVirtualOffset is always less or equal to myEndVirtualOffset private int startVirtualOffset; private int endVirtualOffset; private SelectionMarker(int start, int end) { super(myEditor.getDocument(), start, end, false); myEditor.getCaretModel().mySelectionMarkerTree.addInterval(this, start, end, false, false, false, 0); } private void resetVirtualSelection() { startVirtualOffset = 0; endVirtualOffset = 0; } private boolean hasVirtualSelection() { return endVirtualOffset > startVirtualOffset; } @Override public void dispose() { if (isValid()) { myEditor.getCaretModel().mySelectionMarkerTree.removeInterval(this); } } @Override protected void changedUpdateImpl(@NotNull DocumentEvent e) { super.changedUpdateImpl(e); if (isValid()) { int startOffset = intervalStart(); int endOffset = intervalEnd(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), startOffset)) setIntervalStart(startOffset - 1); if (DocumentUtil.isInsideSurrogatePair(getDocument(), endOffset)) setIntervalStart(endOffset - 1); } if (endVirtualOffset > 0 && isValid()) { Document document = e.getDocument(); int startAfter = intervalStart(); int endAfter = intervalEnd(); if (!DocumentUtil.isAtLineEnd(endAfter, document) || document.getLineNumber(startAfter) != document.getLineNumber(endAfter)) { resetVirtualSelection(); } } } @Override protected void onReTarget(int startOffset, int endOffset, int destOffset) { int start = intervalStart(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), start)) { setIntervalStart(start - 1); } int end = intervalEnd(); if (DocumentUtil.isInsideSurrogatePair(getDocument(), end)) { setIntervalStart(end - 1); } } @Override public String toString() { return super.toString() + (hasVirtualSelection() ? " virtual selection: " + startVirtualOffset + "-" + endVirtualOffset : ""); } } }
IDEA-198066 RegEx. Wrong selection with double click.
platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java
IDEA-198066 RegEx. Wrong selection with double click.
<ide><path>latform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java <ide> <ide> import com.intellij.diagnostic.AttachmentFactory; <ide> import com.intellij.diagnostic.Dumpable; <add>import com.intellij.openapi.actionSystem.ActionManager; <ide> import com.intellij.openapi.actionSystem.IdeActions; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.editor.*; <del>import com.intellij.openapi.editor.actionSystem.EditorActionHandler; <del>import com.intellij.openapi.editor.actionSystem.EditorActionManager; <add>import com.intellij.openapi.editor.actionSystem.EditorAction; <ide> import com.intellij.openapi.editor.actions.EditorActionUtil; <ide> import com.intellij.openapi.editor.event.CaretEvent; <ide> import com.intellij.openapi.editor.event.DocumentEvent; <ide> } <ide> <ide> try { <del> EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); <del> handler.execute(myEditor, this, myEditor.getDataContext()); <add> EditorAction action = (EditorAction)ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); <add> action.actionPerformed(myEditor, myEditor.getDataContext()); <ide> } <ide> finally { <ide> if (needOverrideSetting) {
Java
mpl-2.0
cee5890464f5f2b43d11b369a7e146a7b4b392f5
0
zamojski/TowerCollector,zamojski/TowerCollector
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector; import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Resources.NotFoundException; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.provider.Settings; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ShareCompat; import androidx.core.content.ContextCompat; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout.Tab; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import info.zamojski.soft.towercollector.analytics.IntentSource; import info.zamojski.soft.towercollector.broadcast.AirplaneModeBroadcastReceiver; import info.zamojski.soft.towercollector.broadcast.BatterySaverBroadcastReceiver; import info.zamojski.soft.towercollector.controls.DialogManager; import info.zamojski.soft.towercollector.controls.NonSwipeableViewPager; import info.zamojski.soft.towercollector.dao.MeasurementsDatabase; import info.zamojski.soft.towercollector.enums.ExportAction; import info.zamojski.soft.towercollector.enums.FileType; import info.zamojski.soft.towercollector.enums.MeansOfTransport; import info.zamojski.soft.towercollector.enums.NetworkGroup; import info.zamojski.soft.towercollector.enums.Validity; import info.zamojski.soft.towercollector.events.AirplaneModeChangedEvent; import info.zamojski.soft.towercollector.events.BatteryOptimizationsChangedEvent; import info.zamojski.soft.towercollector.events.CollectorStartedEvent; import info.zamojski.soft.towercollector.events.GpsStatusChangedEvent; import info.zamojski.soft.towercollector.events.MapEnabledChangedEvent; import info.zamojski.soft.towercollector.events.PowerSaveModeChangedEvent; import info.zamojski.soft.towercollector.events.PrintMainWindowEvent; import info.zamojski.soft.towercollector.events.SystemTimeChangedEvent; import info.zamojski.soft.towercollector.model.ChangelogInfo; import info.zamojski.soft.towercollector.model.UpdateInfo; import info.zamojski.soft.towercollector.model.UpdateInfo.DownloadLink; import info.zamojski.soft.towercollector.providers.ChangelogProvider; import info.zamojski.soft.towercollector.providers.HtmlChangelogFormatter; import info.zamojski.soft.towercollector.providers.preferences.PreferencesProvider; import info.zamojski.soft.towercollector.tasks.ExportFileAsyncTask; import info.zamojski.soft.towercollector.tasks.UpdateCheckAsyncTask; import info.zamojski.soft.towercollector.utils.ApkUtils; import info.zamojski.soft.towercollector.utils.BackgroundTaskHelper; import info.zamojski.soft.towercollector.utils.BatteryUtils; import info.zamojski.soft.towercollector.utils.DateUtils; import info.zamojski.soft.towercollector.utils.FileUtils; import info.zamojski.soft.towercollector.utils.GpsUtils; import info.zamojski.soft.towercollector.utils.MapUtils; import info.zamojski.soft.towercollector.utils.NetworkUtils; import info.zamojski.soft.towercollector.utils.PermissionUtils; import info.zamojski.soft.towercollector.utils.StorageUtils; import info.zamojski.soft.towercollector.utils.StringUtils; import info.zamojski.soft.towercollector.utils.UpdateDialogArrayAdapter; import info.zamojski.soft.towercollector.utils.OpenCellIdUtils; import info.zamojski.soft.towercollector.views.MainActivityPagerAdapter; import permissions.dispatcher.NeedsPermission; import permissions.dispatcher.OnNeverAskAgain; import permissions.dispatcher.OnPermissionDenied; import permissions.dispatcher.OnShowRationale; import permissions.dispatcher.PermissionRequest; import permissions.dispatcher.RuntimePermissions; import timber.log.Timber; @RuntimePermissions public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { private static final int BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT = 'B'; private static final int BATTERY_SAVER_ACTIVITY_RESULT = 'S'; private static final int AIRPLANE_MODE_ACTIVITY_RESULT = 'A'; private AtomicBoolean isCollectorServiceRunning = new AtomicBoolean(false); private boolean isGpsEnabled = false; private boolean showAskForLocationSettingsDialog = false; private boolean showNotCompatibleDialog = true; private BroadcastReceiver airplaneModeBroadcastReceiver = new AirplaneModeBroadcastReceiver(); private BroadcastReceiver batterySaverBroadcastReceiver = new BatterySaverBroadcastReceiver();; private String exportedDirAbsolutePath; private String[] exportedFilePaths; private boolean showExportFinishedDialog = false; private Boolean canStartNetworkTypeSystemActivityResult = null; private Menu mainMenu; private MenuItem startMenu; private MenuItem stopMenu; private MenuItem networkTypeMenu; private TabLayout tabLayout; private boolean isMinimized = false; public ICollectorService collectorServiceBinder; private BackgroundTaskHelper backgroundTaskHelper; private NonSwipeableViewPager viewPager; private View activityView; private boolean isFirstStart = true; // ========== ACTIVITY ========== // @Override protected void onCreate(Bundle savedInstanceState) { setTheme(MyApplication.getCurrentAppTheme()); super.onCreate(savedInstanceState); Timber.d("onCreate(): Creating activity"); // set fixed screen orientation if (!ApkUtils.isRunningOnBuggyOreoSetRequestedOrientation(this)) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.main); activityView = findViewById(R.id.main_root); //setup toolbar Toolbar toolbar = findViewById(R.id.main_toolbar); toolbar.setPopupTheme(MyApplication.getCurrentPopupTheme()); setSupportActionBar(toolbar); // setup tabbed layout MainActivityPagerAdapter pageAdapter = new MainActivityPagerAdapter(getSupportFragmentManager(), getApplication()); viewPager = findViewById(R.id.main_pager); viewPager.setAdapter(pageAdapter); tabLayout = findViewById(R.id.main_tab_layout); tabLayout.setupWithViewPager(viewPager); tabLayout.addOnTabSelectedListener(this); backgroundTaskHelper = new BackgroundTaskHelper(this); displayNotCompatibleDialog(); // show latest developer's messages displayDevelopersMessages(); // show introduction displayIntroduction(); processOnStartIntent(getIntent()); // check for availability of new version checkForNewVersionAvailability(); registerReceiver(airplaneModeBroadcastReceiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)); registerReceiver(batterySaverBroadcastReceiver, new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)); } @Override protected void onDestroy() { super.onDestroy(); Timber.d("onDestroy(): Unbinding from service"); if (isCollectorServiceRunning.get()) unbindService(collectorServiceConnection); tabLayout.removeOnTabSelectedListener(this); if (airplaneModeBroadcastReceiver != null) unregisterReceiver(airplaneModeBroadcastReceiver); if (batterySaverBroadcastReceiver != null) unregisterReceiver(batterySaverBroadcastReceiver); } @Override protected void onStart() { super.onStart(); Timber.d("onStart(): Binding to service"); isCollectorServiceRunning.set(MyApplication.isBackgroundTaskRunning(CollectorService.class)); if (isCollectorServiceRunning.get()) { bindService(new Intent(this, CollectorService.class), collectorServiceConnection, 0); } if (isMinimized && showExportFinishedDialog) { displayExportFinishedDialog(); } isMinimized = false; EventBus.getDefault().register(this); String appThemeName = MyApplication.getPreferencesProvider().getAppTheme(); MyApplication.getAnalytics().sendPrefsAppTheme(appThemeName); if (isFirstStart && MyApplication.getPreferencesProvider().getStartCollectorAtStartup()) { isFirstStart = false; startCollectorServiceWithCheck(); } } @Override protected void onStop() { super.onStop(); isMinimized = true; EventBus.getDefault().unregister(this); } @Override protected void onResume() { super.onResume(); Timber.d("onResume(): Resuming"); // print on UI EventBus.getDefault().post(new PrintMainWindowEvent()); // restore recent tab int recentTabIndex = MyApplication.getPreferencesProvider().getMainWindowRecentTab(); viewPager.setCurrentItem(recentTabIndex); // if coming back from Android settings re-run the action if (showAskForLocationSettingsDialog) { startCollectorServiceWithCheck(); } // if keep on is checked if (MyApplication.getPreferencesProvider().getMainKeepScreenOnMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } @Override protected void onPause() { super.onPause(); Timber.d("onPause(): Pausing"); // remember current tab int currentTabIndex = viewPager.getCurrentItem(); MyApplication.getPreferencesProvider().setMainWindowRecentTab(currentTabIndex); } // ========== MENU ========== // @Override public boolean onCreateOptionsMenu(Menu menu) { Timber.d("onCreateOptionsMenu(): Loading action bar"); getMenuInflater().inflate(R.menu.main, menu); // save references startMenu = menu.findItem(R.id.main_menu_start); stopMenu = menu.findItem(R.id.main_menu_stop); networkTypeMenu = menu.findItem(R.id.main_menu_network_type); mainMenu = menu;// store the menu in an local variable for hardware key return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isRunning = isCollectorServiceRunning.get(); Timber.d("onPrepareOptionsMenu(): Preparing action bar menu for running = %s", isRunning); // toggle visibility startMenu.setVisible(!isRunning); stopMenu.setVisible(isRunning); boolean networkTypeAvailable = canStartNetworkTypeSystemActivity(); networkTypeMenu.setVisible(networkTypeAvailable); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // start action int itemId = item.getItemId(); if (itemId == R.id.main_menu_start) { startCollectorServiceWithCheck(); return true; } else if (itemId == R.id.main_menu_stop) { stopCollectorService(); return true; } else if (itemId == R.id.main_menu_upload) { startUploaderServiceWithCheck(); return true; } else if (itemId == R.id.main_menu_export) { startExportAsyncTask(); return true; } else if (itemId == R.id.main_menu_clear) { startCleanup(); return true; } else if (itemId == R.id.main_menu_preferences) { startPreferencesActivity(); return true; } else if (itemId == R.id.main_menu_network_type) { startNetworkTypeSystemActivity(); return true; } else { return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean batteryOptimizationsEnabled = BatteryUtils.areBatteryOptimizationsEnabled(MyApplication.getApplication()); EventBus.getDefault().postSticky(new BatteryOptimizationsChangedEvent(batteryOptimizationsEnabled)); } else if (requestCode == BATTERY_SAVER_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean powerSaveModeEnabled = BatteryUtils.isPowerSaveModeEnabled(MyApplication.getApplication()); EventBus.getDefault().postSticky(new PowerSaveModeChangedEvent(powerSaveModeEnabled)); } else if (requestCode == AIRPLANE_MODE_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean airplaneModeEnabled = NetworkUtils.isInAirplaneMode(MyApplication.getApplication()); EventBus.getDefault().postSticky(new AirplaneModeChangedEvent(airplaneModeEnabled)); } else if (requestCode == StorageUtils.OPEN_DOCUMENT_ACTIVITY_RESULT) { StorageUtils.persistStorageUri(this, resultCode, data); } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); Timber.d("onNewIntent(): New intent received: %s", intent); processOnStartIntent(intent); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (event.getAction() == KeyEvent.ACTION_UP && mainMenu != null) { Timber.i("onKeyUp(): Hardware menu key pressed"); mainMenu.performIdentifierAction(R.id.main_menu_more, 0); return true; } } return super.onKeyUp(keyCode, event); } @Override public void onTabSelected(Tab tab) { Timber.d("onTabSelected() Switching to tab %s", tab.getPosition()); // switch to page when tab is selected viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab) { // nothing } @Override public void onTabReselected(Tab tab) { // nothing } // ========== UI ========== // private void printInvalidSystemTime(ICollectorService collectorServiceBinder) { Validity valid = collectorServiceBinder.isSystemTimeValid(); EventBus.getDefault().postSticky(new SystemTimeChangedEvent(valid)); } private void hideInvalidSystemTime() { EventBus.getDefault().postSticky(new SystemTimeChangedEvent(Validity.Valid)); } private void refreshTabs() { viewPager.getAdapter().notifyDataSetChanged(); } // have to be public to prevent Force Close public void displayHelpOnClick(View view) { int titleId = View.NO_ID; int messageId = View.NO_ID; int additionalMessageId = View.NO_ID; int viewId = view.getId(); if (viewId == R.id.main_gps_status_tablerow) { titleId = R.string.main_help_gps_status_title; messageId = R.string.main_help_gps_status_description; } else if (viewId == R.id.main_invalid_system_time_tablerow) { titleId = R.string.main_help_invalid_system_time_title; messageId = R.string.main_help_invalid_system_time_description; } else if (viewId == R.id.main_stats_today_locations_tablerow) { titleId = R.string.main_help_today_locations_title; messageId = R.string.main_help_today_locations_description; } else if (viewId == R.id.main_stats_today_cells_tablerow) { titleId = R.string.main_help_today_cells_title; messageId = R.string.main_help_today_cells_description; } else if (viewId == R.id.main_stats_local_locations_tablerow) { titleId = R.string.main_help_local_locations_title; messageId = R.string.main_help_local_locations_description; } else if (viewId == R.id.main_stats_local_cells_tablerow) { titleId = R.string.main_help_local_cells_title; messageId = R.string.main_help_local_cells_description; } else if (viewId == R.id.main_stats_global_locations_tablerow) { titleId = R.string.main_help_global_locations_title; messageId = R.string.main_help_global_locations_description; } else if (viewId == R.id.main_stats_global_cells_tablerow) { titleId = R.string.main_help_global_cells_title; messageId = R.string.main_help_global_cells_description; } else if (viewId == R.id.main_last_number_of_cells_tablerow) { titleId = R.string.mail_help_last_number_of_cells_title; messageId = R.string.mail_help_last_number_of_cells_description; } else if (viewId == R.id.main_last_network_type_tablerow1 || viewId == R.id.main_last_network_type_tablerow2) { titleId = R.string.main_help_last_network_type_title; messageId = R.string.main_help_last_network_type_description; } else if (viewId == R.id.main_last_long_cell_id_tablerow1 || viewId == R.id.main_last_long_cell_id_tablerow2) { titleId = R.string.main_help_last_long_cell_id_title; messageId = R.string.main_help_last_long_cell_id_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Lte) { additionalMessageId = R.string.main_help_last_long_cell_id_description_lte; } else if (tag == NetworkGroup.Wcdma) { additionalMessageId = R.string.main_help_last_long_cell_id_description_umts; } } else if (viewId == R.id.main_last_cell_id_rnc_tablerow1 || viewId == R.id.main_last_cell_id_rnc_tablerow2) { titleId = R.string.main_help_last_cell_id_rnc_title; messageId = R.string.main_help_last_cell_id_rnc_description; } else if (viewId == R.id.main_last_cell_id_tablerow1 || viewId == R.id.main_last_cell_id_tablerow2) { titleId = R.string.main_help_last_cell_id_title; messageId = R.string.main_help_last_cell_id_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_bid_title; } } else if (viewId == R.id.main_last_lac_tablerow1 || viewId == R.id.main_last_lac_tablerow2) { titleId = R.string.main_help_last_lac_title; messageId = R.string.main_help_last_lac_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Lte || tag == NetworkGroup.Nr) { titleId = R.string.main_help_last_tac_title; } else if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_nid_title; messageId = R.string.main_help_last_nid_description; } } else if (viewId == R.id.main_last_mcc_tablerow1 || viewId == R.id.main_last_mcc_tablerow2) { titleId = R.string.main_help_last_mcc_title; messageId = R.string.main_help_last_mcc_description; } else if (viewId == R.id.main_last_mnc_tablerow1 || viewId == R.id.main_last_mnc_tablerow2) { titleId = R.string.main_help_last_mnc_title; messageId = R.string.main_help_last_mnc_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_sid_title; messageId = R.string.main_help_last_sid_description; } } else if (viewId == R.id.main_last_signal_strength_tablerow1 || viewId == R.id.main_last_signal_strength_tablerow2) { titleId = R.string.main_help_last_signal_strength_title; messageId = R.string.main_help_last_signal_strength_description; } else if (viewId == R.id.main_last_latitude_tablerow) { titleId = R.string.main_help_last_latitude_title; messageId = R.string.main_help_last_latitude_description; } else if (viewId == R.id.main_last_longitude_tablerow) { titleId = R.string.main_help_last_longitude_title; messageId = R.string.main_help_last_longitude_description; } else if (viewId == R.id.main_last_gps_accuracy_tablerow) { titleId = R.string.main_help_last_gps_accuracy_title; messageId = R.string.main_help_last_gps_accuracy_description; } else if (viewId == R.id.main_last_date_time_tablerow) { titleId = R.string.main_help_last_date_time_title; messageId = R.string.main_help_last_date_time_description; } else if (viewId == R.id.main_stats_to_upload_ocid_locations_tablerow) { titleId = R.string.main_help_to_upload_common_locations_title; messageId = R.string.main_help_to_upload_ocid_locations_description; } else if (viewId == R.id.main_stats_to_upload_mls_locations_tablerow) { titleId = R.string.main_help_to_upload_common_locations_title; messageId = R.string.main_help_to_upload_mls_locations_description; } Timber.d("displayHelpOnClick(): Displaying help for title: %s", titleId); if (titleId != View.NO_ID && messageId != View.NO_ID) { String message = getString(messageId); if (additionalMessageId != View.NO_ID) { message += "\n\n" + getString(additionalMessageId); } AlertDialog dialog = new AlertDialog.Builder(this).setTitle(titleId).setMessage(message).setPositiveButton(R.string.dialog_ok, null).create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } } // have to be public to prevent Force Close public void displayBatteryOptimizationsHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_battery_optimizations_title) .setMessage(R.string.main_help_battery_optimizations_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startBatteryOptimizationsSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } // have to be public to prevent Force Close public void displayPowerSaveModeHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_power_save_mode_title) .setMessage(R.string.main_help_power_save_mode_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startBatterySaverSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } // have to be public to prevent Force Close public void displayAirplaneModeHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_airplane_mode_title) .setMessage(R.string.main_help_airplane_mode_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startAirplaneModeSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } private void displayUploadResultDialog(String descriptionContent) { try { Timber.d("displayUploadResultDialog(): Received extras: %s", descriptionContent); // display dialog AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.uploader_result_dialog_title); alertDialog.setMessage(descriptionContent); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show(); } catch (NotFoundException ex) { Timber.w("displayUploadResultDialog(): Invalid string id received with intent extras: %s", descriptionContent); MyApplication.handleSilentException(ex); } } private void displayNewVersionDownloadOptions(UpdateInfo updateInfo) { // display dialog AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.new_version, null); dialogBuilder.setView(dialogLayout); final AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.updater_dialog_new_version_available); // load data ArrayAdapter<UpdateInfo.DownloadLink> adapter = new UpdateDialogArrayAdapter(alertDialog.getContext(), inflater, updateInfo.getDownloadLinks()); ListView listView = (ListView) dialogLayout.findViewById(R.id.download_options_list); listView.setAdapter(adapter); // bind events final CheckBox disableAutoUpdateCheckCheckbox = (CheckBox) dialogLayout.findViewById(R.id.download_options_disable_auto_update_check_checkbox); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DownloadLink downloadLink = (DownloadLink) parent.getItemAtPosition(position); Timber.d("displayNewVersionDownloadOptions(): Selected position: %s", downloadLink.getLabel()); boolean disableAutoUpdateCheckCheckboxChecked = disableAutoUpdateCheckCheckbox.isChecked(); Timber.d("displayNewVersionDownloadOptions(): Disable update check checkbox checked = %s", disableAutoUpdateCheckCheckboxChecked); if (disableAutoUpdateCheckCheckboxChecked) { MyApplication.getPreferencesProvider().setUpdateCheckEnabled(false); } MyApplication.getAnalytics().sendUpdateAction(downloadLink.getLabel()); String[] links = downloadLink.getLinks(); boolean startActivityFailed = false; for (String link : links) { startActivityFailed = false; try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link))); break; } catch (ActivityNotFoundException ex) { startActivityFailed = true; } } if (startActivityFailed) Toast.makeText(getApplication(), R.string.web_browser_missing, Toast.LENGTH_LONG).show(); alertDialog.dismiss(); } }); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean disableAutoUpdateCheckCheckboxChecked = disableAutoUpdateCheckCheckbox.isChecked(); Timber.d("displayNewVersionDownloadOptions(): Disable update check checkbox checked = %s", disableAutoUpdateCheckCheckboxChecked); if (disableAutoUpdateCheckCheckboxChecked) { MyApplication.getPreferencesProvider().setUpdateCheckEnabled(false); } } }); alertDialog.show(); } private void displayNotCompatibleDialog() { // check if displayed in this app run if (showNotCompatibleDialog) { // check if not disabled in preferences boolean showCompatibilityWarningEnabled = MyApplication.getPreferencesProvider().getShowCompatibilityWarning(); if (showCompatibilityWarningEnabled) { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // check if device contains telephony hardware (some tablets doesn't report even if have) // NOTE: in the future this may need to be expanded when new specific features appear PackageManager packageManager = getPackageManager(); boolean noRadioDetected = !(packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) && (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA))); // show dialog if something is not supported if (noRadioDetected) { Timber.d("displayNotCompatibleDialog(): Not compatible because of radio: %s, phone type: %s", noRadioDetected, telephonyManager.getPhoneType()); //use custom layout to show "don't show this again" checkbox AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.dont_show_again_dialog, null); final CheckBox dontShowAgainCheckbox = (CheckBox) dialogLayout.findViewById(R.id.dont_show_again_dialog_checkbox); dialogBuilder.setView(dialogLayout); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.main_dialog_not_compatible_title); StringBuilder stringBuilder = new StringBuilder(getString(R.string.main_dialog_not_compatible_begin)); if (noRadioDetected) { stringBuilder.append(getString(R.string.main_dialog_no_compatible_mobile_radio_message)); } // text set this way to prevent checkbox from disappearing when text is too long TextView messageTextView = (TextView) dialogLayout.findViewById(R.id.dont_show_again_dialog_textview); messageTextView.setText(stringBuilder.toString()); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean dontShowAgainCheckboxChecked = dontShowAgainCheckbox.isChecked(); Timber.d("displayNotCompatibleDialog(): Don't show again checkbox checked = %s", dontShowAgainCheckboxChecked); if (dontShowAgainCheckboxChecked) { MyApplication.getPreferencesProvider().setShowCompatibilityWarning(false); } } }); alertDialog.show(); } } showNotCompatibleDialog = false; } } private void displayIntroduction() { if (MyApplication.getPreferencesProvider().getShowIntroduction()) { Timber.d("displayIntroduction(): Showing introduction"); DialogManager.createHtmlInfoDialog(this, R.string.info_introduction_title, R.raw.info_introduction_content, false, false).show(); MyApplication.getPreferencesProvider().setShowIntroduction(false); } } private void displayDevelopersMessages() { int previousVersionCode = MyApplication.getPreferencesProvider().getPreviousDeveloperMessagesVersion(); int currentVersionCode = ApkUtils.getApkVersionCode(); if (previousVersionCode != currentVersionCode) { MyApplication.getPreferencesProvider().setRecentDeveloperMessagesVersion(currentVersionCode); // skip recent changes for first startup if (MyApplication.getPreferencesProvider().getShowIntroduction()) { return; } Timber.d("displayDevelopersMessages(): Showing changelog between %s and %s", previousVersionCode, currentVersionCode); ChangelogProvider provider = new ChangelogProvider(getApplication(), R.raw.changelog); ChangelogInfo changelog = provider.getChangelog(previousVersionCode); if (changelog.isEmpty()) return; HtmlChangelogFormatter formatter = new HtmlChangelogFormatter(); String message = formatter.formatChangelog(changelog); DialogInterface.OnClickListener remindLaterAction = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // reset setting for next cold start MyApplication.getPreferencesProvider().setRecentDeveloperMessagesVersion(previousVersionCode); } }; DialogManager.createHtmlInfoDialog(this, R.string.dialog_what_is_new, message, false, false, R.string.dialog_remind_later, remindLaterAction).show(); } } public void displayExportFinishedDialog() { showExportFinishedDialog = false; LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.export_finished_dialog, null); TextView messageTextView = dialogLayout.findViewById(R.id.export_finished_dialog_textview); messageTextView.setText(getString(R.string.export_dialog_finished_message, exportedDirAbsolutePath)); ExportAction recentAction = MyApplication.getPreferencesProvider().getExportAction(); boolean singleFile = exportedFilePaths.length == 1; if (!singleFile && recentAction == ExportAction.Open) recentAction = ExportAction.Keep; final RadioButton keepRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_keep_radiobutton); final RadioButton openRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_open_radiobutton); final RadioButton shareRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_share_radiobutton); openRadioButton.setEnabled(singleFile); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.export_dialog_finished_title); builder.setView(dialogLayout); builder.setCancelable(true); if (recentAction == ExportAction.Share) { builder.setPositiveButton(R.string.dialog_share, (dialog, which) -> { exportShareAction(); dismissExportFinishedDialog(dialog); }); } else if (recentAction == ExportAction.Open) { builder.setPositiveButton(R.string.dialog_open, (dialog, which) -> { exportOpenAction(); dismissExportFinishedDialog(dialog); }); } else { builder.setPositiveButton(R.string.dialog_keep, (dialog, which) -> { exportKeepAction(); dismissExportFinishedDialog(dialog); }); } builder.setNeutralButton(R.string.dialog_upload, (dialog, which) -> { MyApplication.getAnalytics().sendExportUploadAction(); startUploaderServiceWithCheck(); }); builder.setNegativeButton(R.string.dialog_delete, (dialog, which) -> { // show dialog that runs async task AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(this); deleteBuilder.setTitle(R.string.delete_dialog_title); deleteBuilder.setMessage(R.string.delete_dialog_message); deleteBuilder.setPositiveButton(R.string.dialog_ok, (positiveDialog, positiveWhich) -> { MeasurementsDatabase.getInstance(MyApplication.getApplication()).deleteAllMeasurements(); EventBus.getDefault().post(new PrintMainWindowEvent()); MyApplication.getAnalytics().sendExportDeleteAction(); }); deleteBuilder.setNegativeButton(R.string.dialog_cancel, (negativeDialog, id) -> { // cancel }); AlertDialog deleteDialog = deleteBuilder.create(); deleteDialog.setCanceledOnTouchOutside(true); deleteDialog.setCancelable(true); deleteDialog.show(); }); builder.setOnCancelListener(dialog -> { exportKeepAction(); exportedFilePaths = null; }); AlertDialog dialog = builder.create(); ExportAction finalRecentAction = recentAction; dialog.setOnShowListener(dialog1 -> { keepRadioButton.setChecked(finalRecentAction == ExportAction.Keep); openRadioButton.setChecked(finalRecentAction == ExportAction.Open); shareRadioButton.setChecked(finalRecentAction == ExportAction.Share); CompoundButton.OnCheckedChangeListener listener = (buttonView, isChecked) -> { Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (isChecked) { ExportAction newRecentAction; if (buttonView == openRadioButton) { newRecentAction = ExportAction.Open; positiveButton.setText(R.string.dialog_open); positiveButton.setOnClickListener(v -> { exportOpenAction(); dismissExportFinishedDialog(dialog); }); } else if (buttonView == shareRadioButton) { newRecentAction = ExportAction.Share; positiveButton.setText(R.string.dialog_share); positiveButton.setOnClickListener(v -> { exportShareAction(); dismissExportFinishedDialog(dialog); }); } else { newRecentAction = ExportAction.Keep; positiveButton.setText(R.string.dialog_keep); positiveButton.setOnClickListener(v -> { exportKeepAction(); dismissExportFinishedDialog(dialog); }); } MyApplication.getPreferencesProvider().setExportAction(newRecentAction); } }; keepRadioButton.setOnCheckedChangeListener(listener); openRadioButton.setOnCheckedChangeListener(listener); shareRadioButton.setOnCheckedChangeListener(listener); }); dialog.show(); exportedDirAbsolutePath = null; } private void dismissExportFinishedDialog(DialogInterface dialog) { dialog.dismiss(); exportedFilePaths = null; } private void exportKeepAction() { MyApplication.getAnalytics().sendExportKeepAction(); } private void exportOpenAction() { Intent openIntent = new Intent(Intent.ACTION_VIEW); Uri fileUri = Uri.parse(exportedFilePaths[0]); String calculatedMimeType = getApplication().getContentResolver().getType(fileUri); openIntent.setDataAndType(fileUri, calculatedMimeType); openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(openIntent); } catch (Exception ex) { Toast.makeText(getApplication(), R.string.system_toast_no_handler_for_operation, Toast.LENGTH_LONG).show(); } } private void exportShareAction() { MyApplication.getAnalytics().sendExportShareAction(); ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(this); for (String filePath : exportedFilePaths) { Uri fileUri = Uri.parse(filePath); shareIntent.addStream(fileUri); } String calculatedMimeType = FileUtils.getFileMimeType(exportedFilePaths); shareIntent.setType(calculatedMimeType); Intent intent = shareIntent.getIntent(); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, null)); } // ========== MENU START/STOP METHODS ========== // private void startCollectorServiceWithCheck() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startCollectorServiceWithCheck(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } MainActivityPermissionsDispatcher.startCollectorServiceWithPermissionCheck(MainActivity.this); } @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void startCollectorService() { askAndSetGpsEnabled(); if (isGpsEnabled) { Timber.d("startCollectorService(): Air plane mode off, starting service"); // create intent final Intent intent = new Intent(this, CollectorService.class); // pass means of transport inside intent boolean gpsOptimizationsEnabled = MyApplication.getPreferencesProvider().getGpsOptimizationsEnabled(); MeansOfTransport selectedType = (gpsOptimizationsEnabled ? MeansOfTransport.Universal : MeansOfTransport.Fixed); intent.putExtra(CollectorService.INTENT_KEY_TRANSPORT_MODE, selectedType); // pass screen on mode final String keepScreenOnMode = MyApplication.getPreferencesProvider().getCollectorKeepScreenOnMode(); intent.putExtra(CollectorService.INTENT_KEY_KEEP_SCREEN_ON_MODE, keepScreenOnMode); // pass analytics data intent.putExtra(CollectorService.INTENT_KEY_START_INTENT_SOURCE, IntentSource.User); // start service ContextCompat.startForegroundService(this, intent); EventBus.getDefault().post(new CollectorStartedEvent(intent)); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_collector_toggle); } } @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorShowRationale(PermissionRequest request) { onShowRationale(request, R.string.permission_collector_rationale_message); } @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorPermissionDenied() { onStartCollectorPermissionDeniedInternal(); } void onStartCollectorPermissionDeniedInternal() { onPermissionDenied(R.string.permission_collector_denied_message); } @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorNeverAskAgain() { onNeverAskAgain(R.string.permission_collector_never_ask_again_message); } private void stopCollectorService() { stopService(new Intent(this, CollectorService.class)); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_collector_toggle); } private void startUploaderServiceWithCheck() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startUploaderServiceWithCheck(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } final PreferencesProvider preferencesProvider = MyApplication.getPreferencesProvider(); final boolean isOcidUploadEnabled = preferencesProvider.isOpenCellIdUploadEnabled(); final boolean isMlsUploadEnabled = preferencesProvider.isMlsUploadEnabled(); final boolean isReuploadIfUploadFailsEnabled = preferencesProvider.isReuploadIfUploadFailsEnabled(); Timber.i("startUploaderServiceWithCheck(): Upload for OCID = " + isOcidUploadEnabled + ", MLS = " + isMlsUploadEnabled); boolean showConfigurator = preferencesProvider.getShowConfiguratorBeforeUpload(); if (showConfigurator) { Timber.d("startUploaderServiceWithCheck(): Showing upload configurator"); // check API key String apiKey = OpenCellIdUtils.getApiKey(); boolean isApiKeyValid = OpenCellIdUtils.isApiKeyValid(apiKey); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.configure_uploader_dialog, null); final CheckBox ocidUploadCheckbox = dialogLayout.findViewById(R.id.ocid_upload_dialog_checkbox); ocidUploadCheckbox.setChecked(isOcidUploadEnabled); dialogLayout.findViewById(R.id.ocid_invalid_api_key_upload_dialog_textview).setVisibility(isApiKeyValid ? View.GONE : View.VISIBLE); final CheckBox mlsUploadCheckbox = dialogLayout.findViewById(R.id.mls_upload_dialog_checkbox); mlsUploadCheckbox.setChecked(isMlsUploadEnabled); final CheckBox reuploadCheckbox = dialogLayout.findViewById(R.id.reupload_if_upload_fails_upload_dialog_checkbox); reuploadCheckbox.setChecked(isReuploadIfUploadFailsEnabled); final CheckBox dontShowAgainCheckbox = dialogLayout.findViewById(R.id.dont_show_again_dialog_checkbox); AlertDialog alertDialog = new AlertDialog.Builder(this).setView(dialogLayout).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.upload_configurator_dialog_title); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_upload), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { boolean isOcidUploadEnabledTemp = ocidUploadCheckbox.isChecked(); boolean isMlsUploadEnabledTemp = mlsUploadCheckbox.isChecked(); boolean isReuploadIfUploadFailsEnabledTemp = reuploadCheckbox.isChecked(); if (dontShowAgainCheckbox.isChecked()) { preferencesProvider.setOpenCellIdUploadEnabled(isOcidUploadEnabled); preferencesProvider.setMlsUploadEnabled(isMlsUploadEnabled); preferencesProvider.setReuploadIfUploadFailsEnabled(isReuploadIfUploadFailsEnabledTemp); preferencesProvider.setShowConfiguratorBeforeUpload(false); } if (!isOcidUploadEnabledTemp && !isMlsUploadEnabledTemp) { showAllProjectsDisabledMessage(); } else { startUploaderService(isOcidUploadEnabledTemp, isMlsUploadEnabledTemp, isReuploadIfUploadFailsEnabledTemp); } } }); alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.main_menu_preferences_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startPreferencesActivity(); } }); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show(); } else { Timber.d("startUploaderServiceWithCheck(): Using upload configuration from preferences"); if (!isOcidUploadEnabled && !isMlsUploadEnabled) { showAllProjectsDisabledMessage(); } else { startUploaderService(isOcidUploadEnabled, isMlsUploadEnabled, isReuploadIfUploadFailsEnabled); } } } private void showAllProjectsDisabledMessage() { Snackbar snackbar = Snackbar.make(activityView, R.string.uploader_all_projects_disabled, Snackbar.LENGTH_LONG) .setAction(R.string.main_menu_preferences_button, new View.OnClickListener() { @Override public void onClick(View v) { startPreferencesActivity(); } }); // hack for black text on dark grey background View view = snackbar.getView(); TextView tv = view.findViewById(R.id.snackbar_text); tv.setTextColor(Color.WHITE); snackbar.show(); } private void startUploaderService(boolean isOcidUploadEnabled, boolean isMlsUploadEnabled, boolean isReuploadIfUploadFailsEnabled) { // start task if (!MyApplication.isBackgroundTaskRunning(UploaderService.class)) { Intent intent = new Intent(MainActivity.this, UploaderService.class); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TO_OCID, isOcidUploadEnabled); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TO_MLS, isMlsUploadEnabled); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TRY_REUPLOAD, isReuploadIfUploadFailsEnabled); intent.putExtra(UploaderService.INTENT_KEY_START_INTENT_SOURCE, IntentSource.User); ContextCompat.startForegroundService(this, intent); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_uploader_toggle); } else Toast.makeText(getApplication(), R.string.uploader_already_running, Toast.LENGTH_LONG).show(); } void startExportAsyncTask() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startExportAsyncTask(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } Uri storageUri = MyApplication.getPreferencesProvider().getStorageUri(); if (StorageUtils.canWriteStorageUri(storageUri)) { final PreferencesProvider preferencesProvider = MyApplication.getPreferencesProvider(); List<FileType> recentFileTypes = preferencesProvider.getEnabledExportFileTypes(); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.configure_exporter_dialog, null); final CheckBox csvExportCheckbox = dialogLayout.findViewById(R.id.csv_export_dialog_checkbox); csvExportCheckbox.setChecked(recentFileTypes.contains(FileType.Csv)); final CheckBox gpxExportCheckbox = dialogLayout.findViewById(R.id.gpx_export_dialog_checkbox); gpxExportCheckbox.setChecked(recentFileTypes.contains(FileType.Gpx)); final CheckBox kmlExportCheckbox = dialogLayout.findViewById(R.id.kml_export_dialog_checkbox); kmlExportCheckbox.setChecked(recentFileTypes.contains(FileType.Kml)); final CheckBox kmzExportCheckbox = dialogLayout.findViewById(R.id.kmz_export_dialog_checkbox); kmzExportCheckbox.setChecked(recentFileTypes.contains(FileType.Kmz)); final CheckBox csvOcidExportCheckbox = dialogLayout.findViewById(R.id.csv_ocid_export_dialog_checkbox); csvOcidExportCheckbox.setChecked(recentFileTypes.contains(FileType.CsvOcid)); final CheckBox jsonMlsExportCheckbox = dialogLayout.findViewById(R.id.json_mls_export_dialog_checkbox); jsonMlsExportCheckbox.setChecked(recentFileTypes.contains(FileType.JsonMls)); final CheckBox compressExportCheckbox = dialogLayout.findViewById(R.id.compress_export_dialog_checkbox); compressExportCheckbox.setChecked(recentFileTypes.contains(FileType.Compress)); AlertDialog alertDialog = new AlertDialog.Builder(this).setView(dialogLayout).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.export_dialog_format_selection_title); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_export), (dialog, which) -> { List<FileType> selectedFileTypes = new ArrayList<>(); if (csvExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Csv); if (gpxExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Gpx); if (kmlExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Kml); if (kmzExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Kmz); if (csvOcidExportCheckbox.isChecked()) selectedFileTypes.add(FileType.CsvOcid); if (jsonMlsExportCheckbox.isChecked()) selectedFileTypes.add(FileType.JsonMls); if (compressExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Compress); preferencesProvider.setEnabledExportFileTypes(selectedFileTypes); Timber.d("startExportAsyncTask(): User selected positions: %s", TextUtils.join(",", selectedFileTypes)); if (selectedFileTypes.isEmpty()) { Toast.makeText(getApplication(), R.string.export_toast_no_file_types_selected, Toast.LENGTH_LONG).show(); } else { ExportFileAsyncTask task = new ExportFileAsyncTask(MainActivity.this, new InternalMessageHandler(MainActivity.this), selectedFileTypes); task.execute(); } }); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel), (dialog, which) -> { // empty }); alertDialog.show(); } else { StorageUtils.requestStorageUri(this); } } private void startCleanup() { // show dialog that runs async task AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.clear_dialog_title); builder.setMessage(R.string.clear_dialog_message); builder.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MeasurementsDatabase.getInstance(MyApplication.getApplication()).clearAllData(); Toast.makeText(MainActivity.this, R.string.clear_toast_finished, Toast.LENGTH_SHORT).show(); MapUtils.clearMapCache(MainActivity.this); EventBus.getDefault().post(new PrintMainWindowEvent()); } }); builder.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // cancel } }); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } private void startPreferencesActivity() { startActivity(new Intent(this, PreferencesActivity.class)); } private boolean canStartNetworkTypeSystemActivity() { if (canStartNetworkTypeSystemActivityResult == null) { canStartNetworkTypeSystemActivityResult = (createDataRoamingSettingsIntent().resolveActivity(getPackageManager()) != null); } return canStartNetworkTypeSystemActivityResult; } private void startNetworkTypeSystemActivity() { try { startActivity(createDataRoamingSettingsIntent()); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startNetworkTypeSystemActivity(): Could not open Settings to change network type"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } @TargetApi(Build.VERSION_CODES.M) private void startBatteryOptimizationsSystemActivity() { try { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivityForResult(intent, BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startBatteryOptimizationsSystemActivity(): Could not open Settings to change battery optimizations"); showCannotOpenAndroidSettingsDialog(); } } private void startBatterySaverSystemActivity() { try { Intent intent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { intent = new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS); } else { intent = new Intent(); intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$BatterySaverSettingsActivity")); } startActivityForResult(intent, BATTERY_SAVER_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startBatterySaverSystemActivity(): Could not open Settings to disable battery saver"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } @TargetApi(Build.VERSION_CODES.M) private void startAirplaneModeSystemActivity() { try { Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS); startActivityForResult(intent, AIRPLANE_MODE_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startAirplaneModeSystemActivity(): Could not open Settings to change airplane mode"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } private void showCannotOpenAndroidSettingsDialog() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setMessage(R.string.dialog_could_not_open_android_settings).setPositiveButton(R.string.dialog_ok, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.show(); } private Intent createDataRoamingSettingsIntent() { return new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS); } // ========== SERVICE CONNECTIONS ========== // private ServiceConnection collectorServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { Timber.d("onServiceConnected(): Service connection created for %s", name); isCollectorServiceRunning.set(true); // refresh menu status invalidateOptionsMenu(); if (binder instanceof ICollectorService) { collectorServiceBinder = (ICollectorService) binder; // display invalid system time if necessary printInvalidSystemTime(collectorServiceBinder); } } @Override public void onServiceDisconnected(ComponentName name) { Timber.d("onServiceDisconnected(): Service connection destroyed of %s", name); unbindService(collectorServiceConnection); isCollectorServiceRunning.set(false); // refresh menu status invalidateOptionsMenu(); // hide invalid system time message hideInvalidSystemTime(); // release reference to service collectorServiceBinder = null; } }; // ========== PERMISSION REQUEST HANDLING ========== // @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // NOTE: delegate the permission handling to generated method MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults); } private void onShowRationale(final PermissionRequest request, @StringRes int messageResId) { onShowRationale(request, getString(messageResId)); } private void onShowRationale(final PermissionRequest request, String message) { new AlertDialog.Builder(this) .setTitle(R.string.permission_required) .setMessage(message) .setCancelable(true) .setPositiveButton(R.string.dialog_proceed, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { request.proceed(); } }) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { request.cancel(); } }) .show(); } private void onPermissionDenied(@StringRes int messageResId) { Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show(); } private void onNeverAskAgain(@StringRes int messageResId) { new AlertDialog.Builder(this) .setTitle(R.string.permission_denied) .setMessage(messageResId) .setCancelable(true) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PermissionUtils.openAppSettings(MyApplication.getApplication()); } }) .setNegativeButton(R.string.dialog_cancel, null) .show(); } // ========== MISCELLANEOUS ========== // private void askAndSetGpsEnabled() { if (GpsUtils.isGpsEnabled(getApplication())) { Timber.d("askAndSetGpsEnabled(): GPS enabled"); isGpsEnabled = true; showAskForLocationSettingsDialog = false; } else { Timber.d("askAndSetGpsEnabled(): GPS disabled, asking user"); isGpsEnabled = false; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_want_enable_gps).setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Timber.d("askAndSetGpsEnabled(): display settings"); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); try { startActivity(intent); showAskForLocationSettingsDialog = true; } catch (ActivityNotFoundException ex1) { intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); try { startActivity(intent); showAskForLocationSettingsDialog = true; } catch (ActivityNotFoundException ex2) { Timber.w("askAndSetGpsEnabled(): Could not open Settings to enable GPS"); MyApplication.handleSilentException(ex2); AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setMessage(R.string.dialog_could_not_open_android_settings).setPositiveButton(R.string.dialog_ok, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.show(); } } finally { dialog.dismiss(); } } }).setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Timber.d("askAndSetGpsEnabled(): cancel"); dialog.cancel(); if (GpsUtils.isGpsEnabled(getApplication())) { Timber.d("askAndSetGpsEnabled(): provider enabled in the meantime"); startCollectorServiceWithCheck(); } else { isGpsEnabled = false; showAskForLocationSettingsDialog = false; } } }); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } } private void checkForNewVersionAvailability() { boolean isAutoUpdateEnabled = MyApplication.getPreferencesProvider().getUpdateCheckEnabled(); MyApplication.getAnalytics().sendPrefsUpdateCheckEnabled(isAutoUpdateEnabled); if (isAutoUpdateEnabled) { long currentDate = DateUtils.getCurrentDateWithoutTime(); long lastUpdateCheckDate = MyApplication.getPreferencesProvider().getLastUpdateCheckDate(); long diffInDays = DateUtils.getTimeDiff(currentDate, lastUpdateCheckDate); Timber.d("checkForNewVersionAvailability(): Last update check performed on: %s, diff to current in days: %s", new Date(lastUpdateCheckDate), diffInDays); // if currently is at least one day after last check (day, not 24 hrs) if (diffInDays >= 1) { // check if network available if (NetworkUtils.isNetworkAvailable(getApplication())) { int currentVersion = ApkUtils.getApkVersionCode(); String updateFeedUrl = String.format(Locale.ENGLISH, BuildConfig.UPDATE_CHECK_FEED_URI, currentVersion); if (!StringUtils.isNullEmptyOrWhitespace(updateFeedUrl)) { UpdateCheckAsyncTask updateCheckTask = new UpdateCheckAsyncTask(getApplication(), currentVersion); updateCheckTask.execute(updateFeedUrl); } MyApplication.getPreferencesProvider().setLastUpdateCheckDate(currentDate); } else { Timber.d("checkForNewVersionAvailability(): No active network connection"); } } } } private void processOnStartIntent(Intent intent) { if (intent != null) { if (intent.hasExtra(UploaderService.INTENT_KEY_RESULT_DESCRIPTION)) { // display upload result displayUploadResultDialog(intent.getStringExtra(UploaderService.INTENT_KEY_RESULT_DESCRIPTION)); } else if (intent.hasExtra(UpdateCheckAsyncTask.INTENT_KEY_UPDATE_INFO)) { try { // display dialog with download options displayNewVersionDownloadOptions((UpdateInfo) intent.getSerializableExtra(UpdateCheckAsyncTask.INTENT_KEY_UPDATE_INFO)); } catch (Exception ex) { Timber.e(ex, "processOnStartIntent(): Failed to deserialize new version extra, possibly after app upgrade"); } } } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(CollectorStartedEvent event) { bindService(event.getIntent(), collectorServiceConnection, 0); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onEvent(GpsStatusChangedEvent event) { if (!event.isActive()) { isCollectorServiceRunning.set(false); invalidateOptionsMenu(); hideInvalidSystemTime(); } } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onEvent(MapEnabledChangedEvent event) { refreshTabs(); } // ========== INNER OBJECTS ========== // public static class InternalMessageHandler extends Handler { public static final int EXPORT_FINISHED_UI_REFRESH = 0; private MainActivity mainActivity; public InternalMessageHandler(MainActivity mainActivity) { this.mainActivity = mainActivity; } @Override public void handleMessage(Message msg) { switch (msg.what) { case EXPORT_FINISHED_UI_REFRESH: mainActivity.exportedDirAbsolutePath = msg.getData().getString(ExportFileAsyncTask.DIR_PATH); mainActivity.exportedFilePaths = msg.getData().getStringArray(ExportFileAsyncTask.FILE_PATHS); if (!mainActivity.isMinimized) mainActivity.displayExportFinishedDialog(); else mainActivity.showExportFinishedDialog = true; break; } } } }
app/src/main/java/info/zamojski/soft/towercollector/MainActivity.java
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector; import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Resources.NotFoundException; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.provider.Settings; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ShareCompat; import androidx.core.content.ContextCompat; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout.Tab; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import info.zamojski.soft.towercollector.analytics.IntentSource; import info.zamojski.soft.towercollector.broadcast.AirplaneModeBroadcastReceiver; import info.zamojski.soft.towercollector.broadcast.BatterySaverBroadcastReceiver; import info.zamojski.soft.towercollector.controls.DialogManager; import info.zamojski.soft.towercollector.controls.NonSwipeableViewPager; import info.zamojski.soft.towercollector.dao.MeasurementsDatabase; import info.zamojski.soft.towercollector.enums.ExportAction; import info.zamojski.soft.towercollector.enums.FileType; import info.zamojski.soft.towercollector.enums.MeansOfTransport; import info.zamojski.soft.towercollector.enums.NetworkGroup; import info.zamojski.soft.towercollector.enums.Validity; import info.zamojski.soft.towercollector.events.AirplaneModeChangedEvent; import info.zamojski.soft.towercollector.events.BatteryOptimizationsChangedEvent; import info.zamojski.soft.towercollector.events.CollectorStartedEvent; import info.zamojski.soft.towercollector.events.GpsStatusChangedEvent; import info.zamojski.soft.towercollector.events.MapEnabledChangedEvent; import info.zamojski.soft.towercollector.events.PowerSaveModeChangedEvent; import info.zamojski.soft.towercollector.events.PrintMainWindowEvent; import info.zamojski.soft.towercollector.events.SystemTimeChangedEvent; import info.zamojski.soft.towercollector.model.ChangelogInfo; import info.zamojski.soft.towercollector.model.UpdateInfo; import info.zamojski.soft.towercollector.model.UpdateInfo.DownloadLink; import info.zamojski.soft.towercollector.providers.ChangelogProvider; import info.zamojski.soft.towercollector.providers.HtmlChangelogFormatter; import info.zamojski.soft.towercollector.providers.preferences.PreferencesProvider; import info.zamojski.soft.towercollector.tasks.ExportFileAsyncTask; import info.zamojski.soft.towercollector.tasks.UpdateCheckAsyncTask; import info.zamojski.soft.towercollector.utils.ApkUtils; import info.zamojski.soft.towercollector.utils.BackgroundTaskHelper; import info.zamojski.soft.towercollector.utils.BatteryUtils; import info.zamojski.soft.towercollector.utils.DateUtils; import info.zamojski.soft.towercollector.utils.FileUtils; import info.zamojski.soft.towercollector.utils.GpsUtils; import info.zamojski.soft.towercollector.utils.MapUtils; import info.zamojski.soft.towercollector.utils.NetworkUtils; import info.zamojski.soft.towercollector.utils.PermissionUtils; import info.zamojski.soft.towercollector.utils.StorageUtils; import info.zamojski.soft.towercollector.utils.StringUtils; import info.zamojski.soft.towercollector.utils.UpdateDialogArrayAdapter; import info.zamojski.soft.towercollector.utils.OpenCellIdUtils; import info.zamojski.soft.towercollector.views.MainActivityPagerAdapter; import permissions.dispatcher.NeedsPermission; import permissions.dispatcher.OnNeverAskAgain; import permissions.dispatcher.OnPermissionDenied; import permissions.dispatcher.OnShowRationale; import permissions.dispatcher.PermissionRequest; import permissions.dispatcher.RuntimePermissions; import timber.log.Timber; @RuntimePermissions public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { private static final int BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT = 'B'; private static final int BATTERY_SAVER_ACTIVITY_RESULT = 'S'; private static final int AIRPLANE_MODE_ACTIVITY_RESULT = 'A'; private AtomicBoolean isCollectorServiceRunning = new AtomicBoolean(false); private boolean isGpsEnabled = false; private boolean showAskForLocationSettingsDialog = false; private boolean showNotCompatibleDialog = true; private BroadcastReceiver airplaneModeBroadcastReceiver = new AirplaneModeBroadcastReceiver(); private BroadcastReceiver batterySaverBroadcastReceiver = null; private String exportedDirAbsolutePath; private String[] exportedFilePaths; private boolean showExportFinishedDialog = false; private Boolean canStartNetworkTypeSystemActivityResult = null; private Menu mainMenu; private MenuItem startMenu; private MenuItem stopMenu; private MenuItem networkTypeMenu; private TabLayout tabLayout; private boolean isMinimized = false; public ICollectorService collectorServiceBinder; private BackgroundTaskHelper backgroundTaskHelper; private NonSwipeableViewPager viewPager; private View activityView; private boolean isFirstStart = true; // ========== ACTIVITY ========== // @Override protected void onCreate(Bundle savedInstanceState) { setTheme(MyApplication.getCurrentAppTheme()); super.onCreate(savedInstanceState); Timber.d("onCreate(): Creating activity"); // set fixed screen orientation if (!ApkUtils.isRunningOnBuggyOreoSetRequestedOrientation(this)) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.main); activityView = findViewById(R.id.main_root); //setup toolbar Toolbar toolbar = findViewById(R.id.main_toolbar); toolbar.setPopupTheme(MyApplication.getCurrentPopupTheme()); setSupportActionBar(toolbar); // setup tabbed layout MainActivityPagerAdapter pageAdapter = new MainActivityPagerAdapter(getSupportFragmentManager(), getApplication()); viewPager = findViewById(R.id.main_pager); viewPager.setAdapter(pageAdapter); tabLayout = findViewById(R.id.main_tab_layout); tabLayout.setupWithViewPager(viewPager); tabLayout.addOnTabSelectedListener(this); backgroundTaskHelper = new BackgroundTaskHelper(this); displayNotCompatibleDialog(); // show latest developer's messages displayDevelopersMessages(); // show introduction displayIntroduction(); processOnStartIntent(getIntent()); // check for availability of new version checkForNewVersionAvailability(); registerReceiver(airplaneModeBroadcastReceiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { batterySaverBroadcastReceiver = new BatterySaverBroadcastReceiver(); registerReceiver(batterySaverBroadcastReceiver, new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)); } } @Override protected void onDestroy() { super.onDestroy(); Timber.d("onDestroy(): Unbinding from service"); if (isCollectorServiceRunning.get()) unbindService(collectorServiceConnection); tabLayout.removeOnTabSelectedListener(this); if (airplaneModeBroadcastReceiver != null) unregisterReceiver(airplaneModeBroadcastReceiver); if (batterySaverBroadcastReceiver != null) unregisterReceiver(batterySaverBroadcastReceiver); } @Override protected void onStart() { super.onStart(); Timber.d("onStart(): Binding to service"); isCollectorServiceRunning.set(MyApplication.isBackgroundTaskRunning(CollectorService.class)); if (isCollectorServiceRunning.get()) { bindService(new Intent(this, CollectorService.class), collectorServiceConnection, 0); } if (isMinimized && showExportFinishedDialog) { displayExportFinishedDialog(); } isMinimized = false; EventBus.getDefault().register(this); String appThemeName = MyApplication.getPreferencesProvider().getAppTheme(); MyApplication.getAnalytics().sendPrefsAppTheme(appThemeName); if (isFirstStart && MyApplication.getPreferencesProvider().getStartCollectorAtStartup()) { isFirstStart = false; startCollectorServiceWithCheck(); } } @Override protected void onStop() { super.onStop(); isMinimized = true; EventBus.getDefault().unregister(this); } @Override protected void onResume() { super.onResume(); Timber.d("onResume(): Resuming"); // print on UI EventBus.getDefault().post(new PrintMainWindowEvent()); // restore recent tab int recentTabIndex = MyApplication.getPreferencesProvider().getMainWindowRecentTab(); viewPager.setCurrentItem(recentTabIndex); // if coming back from Android settings re-run the action if (showAskForLocationSettingsDialog) { startCollectorServiceWithCheck(); } // if keep on is checked if (MyApplication.getPreferencesProvider().getMainKeepScreenOnMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } @Override protected void onPause() { super.onPause(); Timber.d("onPause(): Pausing"); // remember current tab int currentTabIndex = viewPager.getCurrentItem(); MyApplication.getPreferencesProvider().setMainWindowRecentTab(currentTabIndex); } // ========== MENU ========== // @Override public boolean onCreateOptionsMenu(Menu menu) { Timber.d("onCreateOptionsMenu(): Loading action bar"); getMenuInflater().inflate(R.menu.main, menu); // save references startMenu = menu.findItem(R.id.main_menu_start); stopMenu = menu.findItem(R.id.main_menu_stop); networkTypeMenu = menu.findItem(R.id.main_menu_network_type); mainMenu = menu;// store the menu in an local variable for hardware key return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isRunning = isCollectorServiceRunning.get(); Timber.d("onPrepareOptionsMenu(): Preparing action bar menu for running = %s", isRunning); // toggle visibility startMenu.setVisible(!isRunning); stopMenu.setVisible(isRunning); boolean networkTypeAvailable = canStartNetworkTypeSystemActivity(); networkTypeMenu.setVisible(networkTypeAvailable); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // start action int itemId = item.getItemId(); if (itemId == R.id.main_menu_start) { startCollectorServiceWithCheck(); return true; } else if (itemId == R.id.main_menu_stop) { stopCollectorService(); return true; } else if (itemId == R.id.main_menu_upload) { startUploaderServiceWithCheck(); return true; } else if (itemId == R.id.main_menu_export) { startExportAsyncTask(); return true; } else if (itemId == R.id.main_menu_clear) { startCleanup(); return true; } else if (itemId == R.id.main_menu_preferences) { startPreferencesActivity(); return true; } else if (itemId == R.id.main_menu_network_type) { startNetworkTypeSystemActivity(); return true; } else { return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean batteryOptimizationsEnabled = BatteryUtils.areBatteryOptimizationsEnabled(MyApplication.getApplication()); EventBus.getDefault().postSticky(new BatteryOptimizationsChangedEvent(batteryOptimizationsEnabled)); } else if (requestCode == BATTERY_SAVER_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean powerSaveModeEnabled = BatteryUtils.isPowerSaveModeEnabled(MyApplication.getApplication()); EventBus.getDefault().postSticky(new PowerSaveModeChangedEvent(powerSaveModeEnabled)); } else if (requestCode == AIRPLANE_MODE_ACTIVITY_RESULT) { // don't check resultCode because it's always 0 (user needs to manually navigate back) boolean airplaneModeEnabled = NetworkUtils.isInAirplaneMode(MyApplication.getApplication()); EventBus.getDefault().postSticky(new AirplaneModeChangedEvent(airplaneModeEnabled)); } else if (requestCode == StorageUtils.OPEN_DOCUMENT_ACTIVITY_RESULT) { StorageUtils.persistStorageUri(this, resultCode, data); } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); Timber.d("onNewIntent(): New intent received: %s", intent); processOnStartIntent(intent); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (event.getAction() == KeyEvent.ACTION_UP && mainMenu != null) { Timber.i("onKeyUp(): Hardware menu key pressed"); mainMenu.performIdentifierAction(R.id.main_menu_more, 0); return true; } } return super.onKeyUp(keyCode, event); } @Override public void onTabSelected(Tab tab) { Timber.d("onTabSelected() Switching to tab %s", tab.getPosition()); // switch to page when tab is selected viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab) { // nothing } @Override public void onTabReselected(Tab tab) { // nothing } // ========== UI ========== // private void printInvalidSystemTime(ICollectorService collectorServiceBinder) { Validity valid = collectorServiceBinder.isSystemTimeValid(); EventBus.getDefault().postSticky(new SystemTimeChangedEvent(valid)); } private void hideInvalidSystemTime() { EventBus.getDefault().postSticky(new SystemTimeChangedEvent(Validity.Valid)); } private void refreshTabs() { viewPager.getAdapter().notifyDataSetChanged(); } // have to be public to prevent Force Close public void displayHelpOnClick(View view) { int titleId = View.NO_ID; int messageId = View.NO_ID; int additionalMessageId = View.NO_ID; int viewId = view.getId(); if (viewId == R.id.main_gps_status_tablerow) { titleId = R.string.main_help_gps_status_title; messageId = R.string.main_help_gps_status_description; } else if (viewId == R.id.main_invalid_system_time_tablerow) { titleId = R.string.main_help_invalid_system_time_title; messageId = R.string.main_help_invalid_system_time_description; } else if (viewId == R.id.main_stats_today_locations_tablerow) { titleId = R.string.main_help_today_locations_title; messageId = R.string.main_help_today_locations_description; } else if (viewId == R.id.main_stats_today_cells_tablerow) { titleId = R.string.main_help_today_cells_title; messageId = R.string.main_help_today_cells_description; } else if (viewId == R.id.main_stats_local_locations_tablerow) { titleId = R.string.main_help_local_locations_title; messageId = R.string.main_help_local_locations_description; } else if (viewId == R.id.main_stats_local_cells_tablerow) { titleId = R.string.main_help_local_cells_title; messageId = R.string.main_help_local_cells_description; } else if (viewId == R.id.main_stats_global_locations_tablerow) { titleId = R.string.main_help_global_locations_title; messageId = R.string.main_help_global_locations_description; } else if (viewId == R.id.main_stats_global_cells_tablerow) { titleId = R.string.main_help_global_cells_title; messageId = R.string.main_help_global_cells_description; } else if (viewId == R.id.main_last_number_of_cells_tablerow) { titleId = R.string.mail_help_last_number_of_cells_title; messageId = R.string.mail_help_last_number_of_cells_description; } else if (viewId == R.id.main_last_network_type_tablerow1 || viewId == R.id.main_last_network_type_tablerow2) { titleId = R.string.main_help_last_network_type_title; messageId = R.string.main_help_last_network_type_description; } else if (viewId == R.id.main_last_long_cell_id_tablerow1 || viewId == R.id.main_last_long_cell_id_tablerow2) { titleId = R.string.main_help_last_long_cell_id_title; messageId = R.string.main_help_last_long_cell_id_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Lte) { additionalMessageId = R.string.main_help_last_long_cell_id_description_lte; } else if (tag == NetworkGroup.Wcdma) { additionalMessageId = R.string.main_help_last_long_cell_id_description_umts; } } else if (viewId == R.id.main_last_cell_id_rnc_tablerow1 || viewId == R.id.main_last_cell_id_rnc_tablerow2) { titleId = R.string.main_help_last_cell_id_rnc_title; messageId = R.string.main_help_last_cell_id_rnc_description; } else if (viewId == R.id.main_last_cell_id_tablerow1 || viewId == R.id.main_last_cell_id_tablerow2) { titleId = R.string.main_help_last_cell_id_title; messageId = R.string.main_help_last_cell_id_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_bid_title; } } else if (viewId == R.id.main_last_lac_tablerow1 || viewId == R.id.main_last_lac_tablerow2) { titleId = R.string.main_help_last_lac_title; messageId = R.string.main_help_last_lac_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Lte || tag == NetworkGroup.Nr) { titleId = R.string.main_help_last_tac_title; } else if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_nid_title; messageId = R.string.main_help_last_nid_description; } } else if (viewId == R.id.main_last_mcc_tablerow1 || viewId == R.id.main_last_mcc_tablerow2) { titleId = R.string.main_help_last_mcc_title; messageId = R.string.main_help_last_mcc_description; } else if (viewId == R.id.main_last_mnc_tablerow1 || viewId == R.id.main_last_mnc_tablerow2) { titleId = R.string.main_help_last_mnc_title; messageId = R.string.main_help_last_mnc_description; NetworkGroup tag = (NetworkGroup) view.getTag(); if (tag == NetworkGroup.Cdma) { titleId = R.string.main_help_last_sid_title; messageId = R.string.main_help_last_sid_description; } } else if (viewId == R.id.main_last_signal_strength_tablerow1 || viewId == R.id.main_last_signal_strength_tablerow2) { titleId = R.string.main_help_last_signal_strength_title; messageId = R.string.main_help_last_signal_strength_description; } else if (viewId == R.id.main_last_latitude_tablerow) { titleId = R.string.main_help_last_latitude_title; messageId = R.string.main_help_last_latitude_description; } else if (viewId == R.id.main_last_longitude_tablerow) { titleId = R.string.main_help_last_longitude_title; messageId = R.string.main_help_last_longitude_description; } else if (viewId == R.id.main_last_gps_accuracy_tablerow) { titleId = R.string.main_help_last_gps_accuracy_title; messageId = R.string.main_help_last_gps_accuracy_description; } else if (viewId == R.id.main_last_date_time_tablerow) { titleId = R.string.main_help_last_date_time_title; messageId = R.string.main_help_last_date_time_description; } else if (viewId == R.id.main_stats_to_upload_ocid_locations_tablerow) { titleId = R.string.main_help_to_upload_common_locations_title; messageId = R.string.main_help_to_upload_ocid_locations_description; } else if (viewId == R.id.main_stats_to_upload_mls_locations_tablerow) { titleId = R.string.main_help_to_upload_common_locations_title; messageId = R.string.main_help_to_upload_mls_locations_description; } Timber.d("displayHelpOnClick(): Displaying help for title: %s", titleId); if (titleId != View.NO_ID && messageId != View.NO_ID) { String message = getString(messageId); if (additionalMessageId != View.NO_ID) { message += "\n\n" + getString(additionalMessageId); } AlertDialog dialog = new AlertDialog.Builder(this).setTitle(titleId).setMessage(message).setPositiveButton(R.string.dialog_ok, null).create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } } // have to be public to prevent Force Close public void displayBatteryOptimizationsHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_battery_optimizations_title) .setMessage(R.string.main_help_battery_optimizations_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startBatteryOptimizationsSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } // have to be public to prevent Force Close public void displayPowerSaveModeHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_power_save_mode_title) .setMessage(R.string.main_help_power_save_mode_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startBatterySaverSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } // have to be public to prevent Force Close public void displayAirplaneModeHelpOnClick(View view) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.main_help_airplane_mode_title) .setMessage(R.string.main_help_airplane_mode_description) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startAirplaneModeSystemActivity(); } }) .setNegativeButton(R.string.dialog_cancel, null) .create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } private void displayUploadResultDialog(String descriptionContent) { try { Timber.d("displayUploadResultDialog(): Received extras: %s", descriptionContent); // display dialog AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.uploader_result_dialog_title); alertDialog.setMessage(descriptionContent); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show(); } catch (NotFoundException ex) { Timber.w("displayUploadResultDialog(): Invalid string id received with intent extras: %s", descriptionContent); MyApplication.handleSilentException(ex); } } private void displayNewVersionDownloadOptions(UpdateInfo updateInfo) { // display dialog AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.new_version, null); dialogBuilder.setView(dialogLayout); final AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.updater_dialog_new_version_available); // load data ArrayAdapter<UpdateInfo.DownloadLink> adapter = new UpdateDialogArrayAdapter(alertDialog.getContext(), inflater, updateInfo.getDownloadLinks()); ListView listView = (ListView) dialogLayout.findViewById(R.id.download_options_list); listView.setAdapter(adapter); // bind events final CheckBox disableAutoUpdateCheckCheckbox = (CheckBox) dialogLayout.findViewById(R.id.download_options_disable_auto_update_check_checkbox); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DownloadLink downloadLink = (DownloadLink) parent.getItemAtPosition(position); Timber.d("displayNewVersionDownloadOptions(): Selected position: %s", downloadLink.getLabel()); boolean disableAutoUpdateCheckCheckboxChecked = disableAutoUpdateCheckCheckbox.isChecked(); Timber.d("displayNewVersionDownloadOptions(): Disable update check checkbox checked = %s", disableAutoUpdateCheckCheckboxChecked); if (disableAutoUpdateCheckCheckboxChecked) { MyApplication.getPreferencesProvider().setUpdateCheckEnabled(false); } MyApplication.getAnalytics().sendUpdateAction(downloadLink.getLabel()); String[] links = downloadLink.getLinks(); boolean startActivityFailed = false; for (String link : links) { startActivityFailed = false; try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link))); break; } catch (ActivityNotFoundException ex) { startActivityFailed = true; } } if (startActivityFailed) Toast.makeText(getApplication(), R.string.web_browser_missing, Toast.LENGTH_LONG).show(); alertDialog.dismiss(); } }); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean disableAutoUpdateCheckCheckboxChecked = disableAutoUpdateCheckCheckbox.isChecked(); Timber.d("displayNewVersionDownloadOptions(): Disable update check checkbox checked = %s", disableAutoUpdateCheckCheckboxChecked); if (disableAutoUpdateCheckCheckboxChecked) { MyApplication.getPreferencesProvider().setUpdateCheckEnabled(false); } } }); alertDialog.show(); } private void displayNotCompatibleDialog() { // check if displayed in this app run if (showNotCompatibleDialog) { // check if not disabled in preferences boolean showCompatibilityWarningEnabled = MyApplication.getPreferencesProvider().getShowCompatibilityWarning(); if (showCompatibilityWarningEnabled) { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // check if device contains telephony hardware (some tablets doesn't report even if have) // NOTE: in the future this may need to be expanded when new specific features appear PackageManager packageManager = getPackageManager(); boolean noRadioDetected = !(packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) && (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA))); // show dialog if something is not supported if (noRadioDetected) { Timber.d("displayNotCompatibleDialog(): Not compatible because of radio: %s, phone type: %s", noRadioDetected, telephonyManager.getPhoneType()); //use custom layout to show "don't show this again" checkbox AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.dont_show_again_dialog, null); final CheckBox dontShowAgainCheckbox = (CheckBox) dialogLayout.findViewById(R.id.dont_show_again_dialog_checkbox); dialogBuilder.setView(dialogLayout); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.main_dialog_not_compatible_title); StringBuilder stringBuilder = new StringBuilder(getString(R.string.main_dialog_not_compatible_begin)); if (noRadioDetected) { stringBuilder.append(getString(R.string.main_dialog_no_compatible_mobile_radio_message)); } // text set this way to prevent checkbox from disappearing when text is too long TextView messageTextView = (TextView) dialogLayout.findViewById(R.id.dont_show_again_dialog_textview); messageTextView.setText(stringBuilder.toString()); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { boolean dontShowAgainCheckboxChecked = dontShowAgainCheckbox.isChecked(); Timber.d("displayNotCompatibleDialog(): Don't show again checkbox checked = %s", dontShowAgainCheckboxChecked); if (dontShowAgainCheckboxChecked) { MyApplication.getPreferencesProvider().setShowCompatibilityWarning(false); } } }); alertDialog.show(); } } showNotCompatibleDialog = false; } } private void displayIntroduction() { if (MyApplication.getPreferencesProvider().getShowIntroduction()) { Timber.d("displayIntroduction(): Showing introduction"); DialogManager.createHtmlInfoDialog(this, R.string.info_introduction_title, R.raw.info_introduction_content, false, false).show(); MyApplication.getPreferencesProvider().setShowIntroduction(false); } } private void displayDevelopersMessages() { int previousVersionCode = MyApplication.getPreferencesProvider().getPreviousDeveloperMessagesVersion(); int currentVersionCode = ApkUtils.getApkVersionCode(); if (previousVersionCode != currentVersionCode) { MyApplication.getPreferencesProvider().setRecentDeveloperMessagesVersion(currentVersionCode); // skip recent changes for first startup if (MyApplication.getPreferencesProvider().getShowIntroduction()) { return; } Timber.d("displayDevelopersMessages(): Showing changelog between %s and %s", previousVersionCode, currentVersionCode); ChangelogProvider provider = new ChangelogProvider(getApplication(), R.raw.changelog); ChangelogInfo changelog = provider.getChangelog(previousVersionCode); if (changelog.isEmpty()) return; HtmlChangelogFormatter formatter = new HtmlChangelogFormatter(); String message = formatter.formatChangelog(changelog); DialogInterface.OnClickListener remindLaterAction = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // reset setting for next cold start MyApplication.getPreferencesProvider().setRecentDeveloperMessagesVersion(previousVersionCode); } }; DialogManager.createHtmlInfoDialog(this, R.string.dialog_what_is_new, message, false, false, R.string.dialog_remind_later, remindLaterAction).show(); } } public void displayExportFinishedDialog() { showExportFinishedDialog = false; LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.export_finished_dialog, null); TextView messageTextView = dialogLayout.findViewById(R.id.export_finished_dialog_textview); messageTextView.setText(getString(R.string.export_dialog_finished_message, exportedDirAbsolutePath)); ExportAction recentAction = MyApplication.getPreferencesProvider().getExportAction(); boolean singleFile = exportedFilePaths.length == 1; if (!singleFile && recentAction == ExportAction.Open) recentAction = ExportAction.Keep; final RadioButton keepRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_keep_radiobutton); final RadioButton openRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_open_radiobutton); final RadioButton shareRadioButton = dialogLayout.findViewById(R.id.export_finished_dialog_share_radiobutton); openRadioButton.setEnabled(singleFile); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.export_dialog_finished_title); builder.setView(dialogLayout); builder.setCancelable(true); if (recentAction == ExportAction.Share) { builder.setPositiveButton(R.string.dialog_share, (dialog, which) -> { exportShareAction(); dismissExportFinishedDialog(dialog); }); } else if (recentAction == ExportAction.Open) { builder.setPositiveButton(R.string.dialog_open, (dialog, which) -> { exportOpenAction(); dismissExportFinishedDialog(dialog); }); } else { builder.setPositiveButton(R.string.dialog_keep, (dialog, which) -> { exportKeepAction(); dismissExportFinishedDialog(dialog); }); } builder.setNeutralButton(R.string.dialog_upload, (dialog, which) -> { MyApplication.getAnalytics().sendExportUploadAction(); startUploaderServiceWithCheck(); }); builder.setNegativeButton(R.string.dialog_delete, (dialog, which) -> { // show dialog that runs async task AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(this); deleteBuilder.setTitle(R.string.delete_dialog_title); deleteBuilder.setMessage(R.string.delete_dialog_message); deleteBuilder.setPositiveButton(R.string.dialog_ok, (positiveDialog, positiveWhich) -> { MeasurementsDatabase.getInstance(MyApplication.getApplication()).deleteAllMeasurements(); EventBus.getDefault().post(new PrintMainWindowEvent()); MyApplication.getAnalytics().sendExportDeleteAction(); }); deleteBuilder.setNegativeButton(R.string.dialog_cancel, (negativeDialog, id) -> { // cancel }); AlertDialog deleteDialog = deleteBuilder.create(); deleteDialog.setCanceledOnTouchOutside(true); deleteDialog.setCancelable(true); deleteDialog.show(); }); builder.setOnCancelListener(dialog -> { exportKeepAction(); exportedFilePaths = null; }); AlertDialog dialog = builder.create(); ExportAction finalRecentAction = recentAction; dialog.setOnShowListener(dialog1 -> { keepRadioButton.setChecked(finalRecentAction == ExportAction.Keep); openRadioButton.setChecked(finalRecentAction == ExportAction.Open); shareRadioButton.setChecked(finalRecentAction == ExportAction.Share); CompoundButton.OnCheckedChangeListener listener = (buttonView, isChecked) -> { Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (isChecked) { ExportAction newRecentAction; if (buttonView == openRadioButton) { newRecentAction = ExportAction.Open; positiveButton.setText(R.string.dialog_open); positiveButton.setOnClickListener(v -> { exportOpenAction(); dismissExportFinishedDialog(dialog); }); } else if (buttonView == shareRadioButton) { newRecentAction = ExportAction.Share; positiveButton.setText(R.string.dialog_share); positiveButton.setOnClickListener(v -> { exportShareAction(); dismissExportFinishedDialog(dialog); }); } else { newRecentAction = ExportAction.Keep; positiveButton.setText(R.string.dialog_keep); positiveButton.setOnClickListener(v -> { exportKeepAction(); dismissExportFinishedDialog(dialog); }); } MyApplication.getPreferencesProvider().setExportAction(newRecentAction); } }; keepRadioButton.setOnCheckedChangeListener(listener); openRadioButton.setOnCheckedChangeListener(listener); shareRadioButton.setOnCheckedChangeListener(listener); }); dialog.show(); exportedDirAbsolutePath = null; } private void dismissExportFinishedDialog(DialogInterface dialog) { dialog.dismiss(); exportedFilePaths = null; } private void exportKeepAction() { MyApplication.getAnalytics().sendExportKeepAction(); } private void exportOpenAction() { Intent openIntent = new Intent(Intent.ACTION_VIEW); Uri fileUri = Uri.parse(exportedFilePaths[0]); String calculatedMimeType = getApplication().getContentResolver().getType(fileUri); openIntent.setDataAndType(fileUri, calculatedMimeType); openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(openIntent); } catch (Exception ex) { Toast.makeText(getApplication(), R.string.system_toast_no_handler_for_operation, Toast.LENGTH_LONG).show(); } } private void exportShareAction() { MyApplication.getAnalytics().sendExportShareAction(); ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(this); for (String filePath : exportedFilePaths) { Uri fileUri = Uri.parse(filePath); shareIntent.addStream(fileUri); } String calculatedMimeType = FileUtils.getFileMimeType(exportedFilePaths); shareIntent.setType(calculatedMimeType); Intent intent = shareIntent.getIntent(); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, null)); } // ========== MENU START/STOP METHODS ========== // private void startCollectorServiceWithCheck() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startCollectorServiceWithCheck(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } MainActivityPermissionsDispatcher.startCollectorServiceWithPermissionCheck(MainActivity.this); } @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void startCollectorService() { askAndSetGpsEnabled(); if (isGpsEnabled) { Timber.d("startCollectorService(): Air plane mode off, starting service"); // create intent final Intent intent = new Intent(this, CollectorService.class); // pass means of transport inside intent boolean gpsOptimizationsEnabled = MyApplication.getPreferencesProvider().getGpsOptimizationsEnabled(); MeansOfTransport selectedType = (gpsOptimizationsEnabled ? MeansOfTransport.Universal : MeansOfTransport.Fixed); intent.putExtra(CollectorService.INTENT_KEY_TRANSPORT_MODE, selectedType); // pass screen on mode final String keepScreenOnMode = MyApplication.getPreferencesProvider().getCollectorKeepScreenOnMode(); intent.putExtra(CollectorService.INTENT_KEY_KEEP_SCREEN_ON_MODE, keepScreenOnMode); // pass analytics data intent.putExtra(CollectorService.INTENT_KEY_START_INTENT_SOURCE, IntentSource.User); // start service ContextCompat.startForegroundService(this, intent); EventBus.getDefault().post(new CollectorStartedEvent(intent)); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_collector_toggle); } } @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorShowRationale(PermissionRequest request) { onShowRationale(request, R.string.permission_collector_rationale_message); } @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorPermissionDenied() { onStartCollectorPermissionDeniedInternal(); } void onStartCollectorPermissionDeniedInternal() { onPermissionDenied(R.string.permission_collector_denied_message); } @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE}) void onStartCollectorNeverAskAgain() { onNeverAskAgain(R.string.permission_collector_never_ask_again_message); } private void stopCollectorService() { stopService(new Intent(this, CollectorService.class)); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_collector_toggle); } private void startUploaderServiceWithCheck() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startUploaderServiceWithCheck(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } final PreferencesProvider preferencesProvider = MyApplication.getPreferencesProvider(); final boolean isOcidUploadEnabled = preferencesProvider.isOpenCellIdUploadEnabled(); final boolean isMlsUploadEnabled = preferencesProvider.isMlsUploadEnabled(); final boolean isReuploadIfUploadFailsEnabled = preferencesProvider.isReuploadIfUploadFailsEnabled(); Timber.i("startUploaderServiceWithCheck(): Upload for OCID = " + isOcidUploadEnabled + ", MLS = " + isMlsUploadEnabled); boolean showConfigurator = preferencesProvider.getShowConfiguratorBeforeUpload(); if (showConfigurator) { Timber.d("startUploaderServiceWithCheck(): Showing upload configurator"); // check API key String apiKey = OpenCellIdUtils.getApiKey(); boolean isApiKeyValid = OpenCellIdUtils.isApiKeyValid(apiKey); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.configure_uploader_dialog, null); final CheckBox ocidUploadCheckbox = dialogLayout.findViewById(R.id.ocid_upload_dialog_checkbox); ocidUploadCheckbox.setChecked(isOcidUploadEnabled); dialogLayout.findViewById(R.id.ocid_invalid_api_key_upload_dialog_textview).setVisibility(isApiKeyValid ? View.GONE : View.VISIBLE); final CheckBox mlsUploadCheckbox = dialogLayout.findViewById(R.id.mls_upload_dialog_checkbox); mlsUploadCheckbox.setChecked(isMlsUploadEnabled); final CheckBox reuploadCheckbox = dialogLayout.findViewById(R.id.reupload_if_upload_fails_upload_dialog_checkbox); reuploadCheckbox.setChecked(isReuploadIfUploadFailsEnabled); final CheckBox dontShowAgainCheckbox = dialogLayout.findViewById(R.id.dont_show_again_dialog_checkbox); AlertDialog alertDialog = new AlertDialog.Builder(this).setView(dialogLayout).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.upload_configurator_dialog_title); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_upload), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { boolean isOcidUploadEnabledTemp = ocidUploadCheckbox.isChecked(); boolean isMlsUploadEnabledTemp = mlsUploadCheckbox.isChecked(); boolean isReuploadIfUploadFailsEnabledTemp = reuploadCheckbox.isChecked(); if (dontShowAgainCheckbox.isChecked()) { preferencesProvider.setOpenCellIdUploadEnabled(isOcidUploadEnabled); preferencesProvider.setMlsUploadEnabled(isMlsUploadEnabled); preferencesProvider.setReuploadIfUploadFailsEnabled(isReuploadIfUploadFailsEnabledTemp); preferencesProvider.setShowConfiguratorBeforeUpload(false); } if (!isOcidUploadEnabledTemp && !isMlsUploadEnabledTemp) { showAllProjectsDisabledMessage(); } else { startUploaderService(isOcidUploadEnabledTemp, isMlsUploadEnabledTemp, isReuploadIfUploadFailsEnabledTemp); } } }); alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.main_menu_preferences_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startPreferencesActivity(); } }); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show(); } else { Timber.d("startUploaderServiceWithCheck(): Using upload configuration from preferences"); if (!isOcidUploadEnabled && !isMlsUploadEnabled) { showAllProjectsDisabledMessage(); } else { startUploaderService(isOcidUploadEnabled, isMlsUploadEnabled, isReuploadIfUploadFailsEnabled); } } } private void showAllProjectsDisabledMessage() { Snackbar snackbar = Snackbar.make(activityView, R.string.uploader_all_projects_disabled, Snackbar.LENGTH_LONG) .setAction(R.string.main_menu_preferences_button, new View.OnClickListener() { @Override public void onClick(View v) { startPreferencesActivity(); } }); // hack for black text on dark grey background View view = snackbar.getView(); TextView tv = view.findViewById(R.id.snackbar_text); tv.setTextColor(Color.WHITE); snackbar.show(); } private void startUploaderService(boolean isOcidUploadEnabled, boolean isMlsUploadEnabled, boolean isReuploadIfUploadFailsEnabled) { // start task if (!MyApplication.isBackgroundTaskRunning(UploaderService.class)) { Intent intent = new Intent(MainActivity.this, UploaderService.class); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TO_OCID, isOcidUploadEnabled); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TO_MLS, isMlsUploadEnabled); intent.putExtra(UploaderService.INTENT_KEY_UPLOAD_TRY_REUPLOAD, isReuploadIfUploadFailsEnabled); intent.putExtra(UploaderService.INTENT_KEY_START_INTENT_SOURCE, IntentSource.User); ContextCompat.startForegroundService(this, intent); ApkUtils.reportShortcutUsage(MyApplication.getApplication(), R.string.shortcut_id_uploader_toggle); } else Toast.makeText(getApplication(), R.string.uploader_already_running, Toast.LENGTH_LONG).show(); } void startExportAsyncTask() { String runningTaskClassName = MyApplication.getBackgroundTaskName(); if (runningTaskClassName != null) { Timber.d("startExportAsyncTask(): Another task is running in background: %s", runningTaskClassName); backgroundTaskHelper.showTaskRunningMessage(runningTaskClassName); return; } Uri storageUri = MyApplication.getPreferencesProvider().getStorageUri(); if (StorageUtils.canWriteStorageUri(storageUri)) { final PreferencesProvider preferencesProvider = MyApplication.getPreferencesProvider(); List<FileType> recentFileTypes = preferencesProvider.getEnabledExportFileTypes(); LayoutInflater inflater = LayoutInflater.from(this); View dialogLayout = inflater.inflate(R.layout.configure_exporter_dialog, null); final CheckBox csvExportCheckbox = dialogLayout.findViewById(R.id.csv_export_dialog_checkbox); csvExportCheckbox.setChecked(recentFileTypes.contains(FileType.Csv)); final CheckBox gpxExportCheckbox = dialogLayout.findViewById(R.id.gpx_export_dialog_checkbox); gpxExportCheckbox.setChecked(recentFileTypes.contains(FileType.Gpx)); final CheckBox kmlExportCheckbox = dialogLayout.findViewById(R.id.kml_export_dialog_checkbox); kmlExportCheckbox.setChecked(recentFileTypes.contains(FileType.Kml)); final CheckBox kmzExportCheckbox = dialogLayout.findViewById(R.id.kmz_export_dialog_checkbox); kmzExportCheckbox.setChecked(recentFileTypes.contains(FileType.Kmz)); final CheckBox csvOcidExportCheckbox = dialogLayout.findViewById(R.id.csv_ocid_export_dialog_checkbox); csvOcidExportCheckbox.setChecked(recentFileTypes.contains(FileType.CsvOcid)); final CheckBox jsonMlsExportCheckbox = dialogLayout.findViewById(R.id.json_mls_export_dialog_checkbox); jsonMlsExportCheckbox.setChecked(recentFileTypes.contains(FileType.JsonMls)); final CheckBox compressExportCheckbox = dialogLayout.findViewById(R.id.compress_export_dialog_checkbox); compressExportCheckbox.setChecked(recentFileTypes.contains(FileType.Compress)); AlertDialog alertDialog = new AlertDialog.Builder(this).setView(dialogLayout).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.setTitle(R.string.export_dialog_format_selection_title); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.dialog_export), (dialog, which) -> { List<FileType> selectedFileTypes = new ArrayList<>(); if (csvExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Csv); if (gpxExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Gpx); if (kmlExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Kml); if (kmzExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Kmz); if (csvOcidExportCheckbox.isChecked()) selectedFileTypes.add(FileType.CsvOcid); if (jsonMlsExportCheckbox.isChecked()) selectedFileTypes.add(FileType.JsonMls); if (compressExportCheckbox.isChecked()) selectedFileTypes.add(FileType.Compress); preferencesProvider.setEnabledExportFileTypes(selectedFileTypes); Timber.d("startExportAsyncTask(): User selected positions: %s", TextUtils.join(",", selectedFileTypes)); if (selectedFileTypes.isEmpty()) { Toast.makeText(getApplication(), R.string.export_toast_no_file_types_selected, Toast.LENGTH_LONG).show(); } else { ExportFileAsyncTask task = new ExportFileAsyncTask(MainActivity.this, new InternalMessageHandler(MainActivity.this), selectedFileTypes); task.execute(); } }); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel), (dialog, which) -> { // empty }); alertDialog.show(); } else { StorageUtils.requestStorageUri(this); } } private void startCleanup() { // show dialog that runs async task AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.clear_dialog_title); builder.setMessage(R.string.clear_dialog_message); builder.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MeasurementsDatabase.getInstance(MyApplication.getApplication()).clearAllData(); Toast.makeText(MainActivity.this, R.string.clear_toast_finished, Toast.LENGTH_SHORT).show(); MapUtils.clearMapCache(MainActivity.this); EventBus.getDefault().post(new PrintMainWindowEvent()); } }); builder.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // cancel } }); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } private void startPreferencesActivity() { startActivity(new Intent(this, PreferencesActivity.class)); } private boolean canStartNetworkTypeSystemActivity() { if (canStartNetworkTypeSystemActivityResult == null) { canStartNetworkTypeSystemActivityResult = (createDataRoamingSettingsIntent().resolveActivity(getPackageManager()) != null); } return canStartNetworkTypeSystemActivityResult; } private void startNetworkTypeSystemActivity() { try { startActivity(createDataRoamingSettingsIntent()); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startNetworkTypeSystemActivity(): Could not open Settings to change network type"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } @TargetApi(Build.VERSION_CODES.M) private void startBatteryOptimizationsSystemActivity() { try { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivityForResult(intent, BATTERY_OPTIMIZATIONS_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startBatteryOptimizationsSystemActivity(): Could not open Settings to change battery optimizations"); showCannotOpenAndroidSettingsDialog(); } } private void startBatterySaverSystemActivity() { try { Intent intent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { intent = new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS); } else { intent = new Intent(); intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$BatterySaverSettingsActivity")); } startActivityForResult(intent, BATTERY_SAVER_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startBatterySaverSystemActivity(): Could not open Settings to disable battery saver"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } @TargetApi(Build.VERSION_CODES.M) private void startAirplaneModeSystemActivity() { try { Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS); startActivityForResult(intent, AIRPLANE_MODE_ACTIVITY_RESULT); } catch (ActivityNotFoundException ex) { Timber.w(ex, "startAirplaneModeSystemActivity(): Could not open Settings to change airplane mode"); MyApplication.handleSilentException(ex); showCannotOpenAndroidSettingsDialog(); } } private void showCannotOpenAndroidSettingsDialog() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setMessage(R.string.dialog_could_not_open_android_settings).setPositiveButton(R.string.dialog_ok, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.show(); } private Intent createDataRoamingSettingsIntent() { return new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS); } // ========== SERVICE CONNECTIONS ========== // private ServiceConnection collectorServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { Timber.d("onServiceConnected(): Service connection created for %s", name); isCollectorServiceRunning.set(true); // refresh menu status invalidateOptionsMenu(); if (binder instanceof ICollectorService) { collectorServiceBinder = (ICollectorService) binder; // display invalid system time if necessary printInvalidSystemTime(collectorServiceBinder); } } @Override public void onServiceDisconnected(ComponentName name) { Timber.d("onServiceDisconnected(): Service connection destroyed of %s", name); unbindService(collectorServiceConnection); isCollectorServiceRunning.set(false); // refresh menu status invalidateOptionsMenu(); // hide invalid system time message hideInvalidSystemTime(); // release reference to service collectorServiceBinder = null; } }; // ========== PERMISSION REQUEST HANDLING ========== // @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // NOTE: delegate the permission handling to generated method MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults); } private void onShowRationale(final PermissionRequest request, @StringRes int messageResId) { onShowRationale(request, getString(messageResId)); } private void onShowRationale(final PermissionRequest request, String message) { new AlertDialog.Builder(this) .setTitle(R.string.permission_required) .setMessage(message) .setCancelable(true) .setPositiveButton(R.string.dialog_proceed, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { request.proceed(); } }) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { request.cancel(); } }) .show(); } private void onPermissionDenied(@StringRes int messageResId) { Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show(); } private void onNeverAskAgain(@StringRes int messageResId) { new AlertDialog.Builder(this) .setTitle(R.string.permission_denied) .setMessage(messageResId) .setCancelable(true) .setPositiveButton(R.string.dialog_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PermissionUtils.openAppSettings(MyApplication.getApplication()); } }) .setNegativeButton(R.string.dialog_cancel, null) .show(); } // ========== MISCELLANEOUS ========== // private void askAndSetGpsEnabled() { if (GpsUtils.isGpsEnabled(getApplication())) { Timber.d("askAndSetGpsEnabled(): GPS enabled"); isGpsEnabled = true; showAskForLocationSettingsDialog = false; } else { Timber.d("askAndSetGpsEnabled(): GPS disabled, asking user"); isGpsEnabled = false; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_want_enable_gps).setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Timber.d("askAndSetGpsEnabled(): display settings"); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); try { startActivity(intent); showAskForLocationSettingsDialog = true; } catch (ActivityNotFoundException ex1) { intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); try { startActivity(intent); showAskForLocationSettingsDialog = true; } catch (ActivityNotFoundException ex2) { Timber.w("askAndSetGpsEnabled(): Could not open Settings to enable GPS"); MyApplication.handleSilentException(ex2); AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setMessage(R.string.dialog_could_not_open_android_settings).setPositiveButton(R.string.dialog_ok, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setCancelable(true); alertDialog.show(); } } finally { dialog.dismiss(); } } }).setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Timber.d("askAndSetGpsEnabled(): cancel"); dialog.cancel(); if (GpsUtils.isGpsEnabled(getApplication())) { Timber.d("askAndSetGpsEnabled(): provider enabled in the meantime"); startCollectorServiceWithCheck(); } else { isGpsEnabled = false; showAskForLocationSettingsDialog = false; } } }); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.setCancelable(true); dialog.show(); } } private void checkForNewVersionAvailability() { boolean isAutoUpdateEnabled = MyApplication.getPreferencesProvider().getUpdateCheckEnabled(); MyApplication.getAnalytics().sendPrefsUpdateCheckEnabled(isAutoUpdateEnabled); if (isAutoUpdateEnabled) { long currentDate = DateUtils.getCurrentDateWithoutTime(); long lastUpdateCheckDate = MyApplication.getPreferencesProvider().getLastUpdateCheckDate(); long diffInDays = DateUtils.getTimeDiff(currentDate, lastUpdateCheckDate); Timber.d("checkForNewVersionAvailability(): Last update check performed on: %s, diff to current in days: %s", new Date(lastUpdateCheckDate), diffInDays); // if currently is at least one day after last check (day, not 24 hrs) if (diffInDays >= 1) { // check if network available if (NetworkUtils.isNetworkAvailable(getApplication())) { int currentVersion = ApkUtils.getApkVersionCode(); String updateFeedUrl = String.format(Locale.ENGLISH, BuildConfig.UPDATE_CHECK_FEED_URI, currentVersion); if (!StringUtils.isNullEmptyOrWhitespace(updateFeedUrl)) { UpdateCheckAsyncTask updateCheckTask = new UpdateCheckAsyncTask(getApplication(), currentVersion); updateCheckTask.execute(updateFeedUrl); } MyApplication.getPreferencesProvider().setLastUpdateCheckDate(currentDate); } else { Timber.d("checkForNewVersionAvailability(): No active network connection"); } } } } private void processOnStartIntent(Intent intent) { if (intent != null) { if (intent.hasExtra(UploaderService.INTENT_KEY_RESULT_DESCRIPTION)) { // display upload result displayUploadResultDialog(intent.getStringExtra(UploaderService.INTENT_KEY_RESULT_DESCRIPTION)); } else if (intent.hasExtra(UpdateCheckAsyncTask.INTENT_KEY_UPDATE_INFO)) { try { // display dialog with download options displayNewVersionDownloadOptions((UpdateInfo) intent.getSerializableExtra(UpdateCheckAsyncTask.INTENT_KEY_UPDATE_INFO)); } catch (Exception ex) { Timber.e(ex, "processOnStartIntent(): Failed to deserialize new version extra, possibly after app upgrade"); } } } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(CollectorStartedEvent event) { bindService(event.getIntent(), collectorServiceConnection, 0); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onEvent(GpsStatusChangedEvent event) { if (!event.isActive()) { isCollectorServiceRunning.set(false); invalidateOptionsMenu(); hideInvalidSystemTime(); } } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onEvent(MapEnabledChangedEvent event) { refreshTabs(); } // ========== INNER OBJECTS ========== // public static class InternalMessageHandler extends Handler { public static final int EXPORT_FINISHED_UI_REFRESH = 0; private MainActivity mainActivity; public InternalMessageHandler(MainActivity mainActivity) { this.mainActivity = mainActivity; } @Override public void handleMessage(Message msg) { switch (msg.what) { case EXPORT_FINISHED_UI_REFRESH: mainActivity.exportedDirAbsolutePath = msg.getData().getString(ExportFileAsyncTask.DIR_PATH); mainActivity.exportedFilePaths = msg.getData().getStringArray(ExportFileAsyncTask.FILE_PATHS); if (!mainActivity.isMinimized) mainActivity.displayExportFinishedDialog(); else mainActivity.showExportFinishedDialog = true; break; } } } }
Remove unused condition.
app/src/main/java/info/zamojski/soft/towercollector/MainActivity.java
Remove unused condition.
<ide><path>pp/src/main/java/info/zamojski/soft/towercollector/MainActivity.java <ide> private boolean showNotCompatibleDialog = true; <ide> <ide> private BroadcastReceiver airplaneModeBroadcastReceiver = new AirplaneModeBroadcastReceiver(); <del> private BroadcastReceiver batterySaverBroadcastReceiver = null; <add> private BroadcastReceiver batterySaverBroadcastReceiver = new BatterySaverBroadcastReceiver();; <ide> <ide> private String exportedDirAbsolutePath; <ide> private String[] exportedFilePaths; <ide> checkForNewVersionAvailability(); <ide> <ide> registerReceiver(airplaneModeBroadcastReceiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)); <del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <del> batterySaverBroadcastReceiver = new BatterySaverBroadcastReceiver(); <del> registerReceiver(batterySaverBroadcastReceiver, new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)); <del> } <add> registerReceiver(batterySaverBroadcastReceiver, new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)); <ide> } <ide> <ide> @Override
JavaScript
mit
75842d85449948ad407e96f1aff1633fd5eacb87
0
googlefonts/opentype.js,nodebox/opentype.js,TrompoGames/opentype.js,byte-foundry/opentype.js,felipesanches/opentype.js,fpirsch/opentype.js,moyogo/opentype.js,jacobmarshall/opentype.js,Pomax/opentype.js,mcanthony/opentype.js,axkibe/opentype.js,miguelsousa/opentype.js,moyogo/opentype.js,googlefonts/opentype.js,fpirsch/opentype.js,axkibe/opentype.js,Jolg42/opentype.js,brawer/opentype.js,felipesanches/opentype.js,dhowe/opentype.js,luisbrito/opentype.js,luisbrito/opentype.js,Jolg42/opentype.js,TrompoGames/opentype.js,nodebox/opentype.js,Pomax/opentype.js,miguelsousa/opentype.js,brawer/opentype.js,mcanthony/opentype.js,jacobmarshall/opentype.js,dhowe/opentype.js,byte-foundry/opentype.js
// opentype.js 0.0.1 // https://github.com/nodebox/opentype.js // (c) 2013 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /*jslint bitwise: true */ /*global exports,DataView,document */ (function (exports) { 'use strict'; var opentype, dataTypes, typeOffsets; opentype = exports; // Precondition function that checks if the given predicate is true. // If not, it will log an error message to the console. function checkArgument(predicate, message) { if (!predicate) { throw new Error(message); } } function Path() { this.commands = []; this.fill = 'black'; this.stroke = null; this.strokeWidth = 1; } Path.prototype.moveTo = function (x, y) { this.commands.push({type: 'M', x: x, y: y}); }; Path.prototype.lineTo = function (x, y) { this.commands.push({type: 'L', x: x, y: y}); }; Path.prototype.curveTo = Path.prototype.bezierCurveTo = function (x1, y1, x2, y2, x, y) { this.commands.push({type: 'C', x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y}); }; Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function (x1, y1, x, y) { this.commands.push({type: 'Q', x1: x1, y1: y1, x: x, y: y}); }; Path.prototype.close = Path.prototype.closePath = function () { this.commands.push({type: 'Z'}); }; Path.prototype.extend = function (pathOrCommands) { if (pathOrCommands.commands) { pathOrCommands = pathOrCommands.commands; } this.commands.push.apply(this.commands, pathOrCommands); }; // Draw the path to a 2D context. Path.prototype.draw = function (ctx) { var i, cmd; ctx.beginPath(); for (i = 0; i < this.commands.length; i += 1) { cmd = this.commands[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; Path.prototype.drawPoints = function (ctx) { var i, cmd, blueCircles, redCircles; blueCircles = []; redCircles = []; for (i = 0; i < this.commands.length; i += 1) { cmd = this.commands[i]; if (cmd.type === 'M') { blueCircles.push(cmd); } else if (cmd.type === 'L') { blueCircles.push(cmd); } else if (cmd.type === 'C') { redCircles.push(cmd); } else if (cmd.type === 'Q') { redCircles.push(cmd); } } function drawCircles(l) { var j, PI_SQ = Math.PI * 2; ctx.beginPath(); for (j = 0; j < l.length; j += 1) { ctx.moveTo(l[j].x, l[j].y); ctx.arc(l[j].x, l[j].y, 2, 0, PI_SQ, false); } ctx.closePath(); ctx.fill(); } ctx.fillStyle = 'blue'; drawCircles(blueCircles); ctx.fillStyle = 'red'; drawCircles(redCircles); }; function getByte(dataView, offset) { return dataView.getUint8(offset); } function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } function getShort(dataView, offset) { return dataView.getInt16(offset, false); } function getULong(dataView, offset) { return dataView.getUint32(offset, false); } function getFixed(dataView, offset) { return -1; } function getLongDateTime(dataView, offset) { var v1, v2; v1 = dataView.getUint32(offset, false); v2 = dataView.getUint32(offset + 1, false); return [v1, v2]; } function getTag(dataView, offset) { var tag = '', i; for (i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(dataView.getInt8(i)); } return tag; } dataTypes = { byte: getByte, uShort: getUShort, short: getShort, uLong: getULong, fixed: getFixed, longDateTime: getLongDateTime, tag: getTag }; typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; // A stateful parser that changes the offset whenever a value is retrieved. function Parser(dataView, offset) { this.dataView = dataView; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parse = function (type) { var parseFn, v; parseFn = dataTypes[type]; v = parseFn(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += typeOffsets[type]; return v; }; Parser.prototype.parseByte = function () { var v = getByte(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseUShort = function () { var v = getUShort(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseShort = function () { var v = getShort(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function () { var v = getULong(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.skip = function (type, amount) { if (amount === undefined) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; // Return true if the value at the given bit index is set. function isBitSet(b, bitIndex) { return ((b >> bitIndex) & 1) === 1; } // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBit, sameBit) { var v; if (isBitSet(flag, shortVectorBit)) { // The coordinate is 1 byte long. v = p.parse('byte'); // The `same` bit is re-used for short values to signify the sign of the value. if (!isBitSet(flag, sameBit)) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if (isBitSet(flag, sameBit)) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parse('short'); } } return v; } // Parse an OpenType glyph (described in the glyf table). // Due to the complexity of the parsing we can't define the glyf table declaratively. // The offset is the absolute byte offset of the glyph: the base of the glyph table + the relative offset of the glyph. // http://www.microsoft.com/typography/otspec/glyf.htm function parseGlyph(data, start, index) { var p, glyph, flag, i, j, flags, endPointIndices, numberOfCoordinates, repeatCount, points, point, px, py, component, moreComponents, arg1, arg2, scale, xScale, yScale, scale01, scale10; p = new Parser(data, start); glyph = {}; glyph.index = index; glyph.numberOfContours = p.parseShort(); glyph.xMin = p.parseShort(); glyph.yMin = p.parseShort(); glyph.xMax = p.parseShort(); glyph.yMax = p.parseShort(); if (glyph.numberOfContours > 0) { // This glyph is not a composite. endPointIndices = glyph.endPointIndices = []; for (i = 0; i < glyph.numberOfContours; i += 1) { endPointIndices.push(p.parseUShort()); } glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (i = 0; i < numberOfCoordinates; i += 1) { flag = p.parseByte(); flags.push(flag); // If bit 3 is set, we repeat this flag n times, where n is the next byte. if (isBitSet(flag, 3)) { repeatCount = p.parseByte(); for (j = 0; j < repeatCount; j += 1) { flags.push(flag); i += 1; } } } checkArgument(flags.length === numberOfCoordinates, 'Bad flags.'); if (endPointIndices.length > 0) { points = []; // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if (numberOfCoordinates > 0) { for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = {}; point.onCurve = isBitSet(flag, 0); point.lastPointOfContour = endPointIndices.indexOf(i) >= 0; points.push(point); } px = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.x = parseGlyphCoordinate(p, flag, px, 1, 4); px = point.x; } py = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.y = parseGlyphCoordinate(p, flag, py, 2, 5); py = point.y; } } glyph.points = points; } else { glyph.points = []; } } else if (glyph.numberOfContours === 0) { glyph.points = []; } else { glyph.isComposite = true; glyph.points = []; glyph.components = []; moreComponents = true; while (moreComponents) { component = {}; flags = p.parseUShort(); component.glyphIndex = p.parseUShort(); if (isBitSet(flags, 0)) { // The arguments are words arg1 = p.parseShort(); arg2 = p.parseShort(); component.dx = arg1; component.dy = arg2; } else { // The arguments are bytes arg1 = p.parseByte(); arg2 = p.parseByte(); component.dx = arg1; component.dy = arg2; } if (isBitSet(flags, 3)) { // We have a scale // TODO parse in 16-bit signed fixed number with the low 14 bits of fraction (2.14). scale = p.parseShort(); } else if (isBitSet(flags, 6)) { // We have an X / Y scale xScale = p.parseShort(); yScale = p.parseShort(); } else if (isBitSet(flags, 7)) { // We have a 2x2 transformation xScale = p.parseShort(); scale01 = p.parseShort(); scale10 = p.parseShort(); yScale = p.parseShort(); } glyph.components.push(component); moreComponents = isBitSet(flags, 5); } } return glyph; } // Transform an array of points and return a new array. function transformPoints(points, dx, dy) { var newPoints, i, pt, newPt; newPoints = []; for (i = 0; i < points.length; i += 1) { pt = points[i]; newPt = { x: pt.x + dx, y: pt.y + dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } // Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data, start, loca) { var glyphs, i, j, offset, nextOffset, glyph, component, componentGlyph, transformedPoints; glyphs = []; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { offset = loca[i]; nextOffset = loca[i + 1]; if (offset !== nextOffset) { glyphs.push(parseGlyph(data, start + offset, i)); } else { glyphs.push({index: i, numberOfContours: 0, xMin: 0, xMax: 0, yMin: 0, yMax: 0}); } } // Go over the glyphs again, resolving the composite glyphs. for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; if (glyph.isComposite) { for (j = 0; j < glyph.components.length; j += 1) { component = glyph.components[j]; componentGlyph = glyphs[component.glyphIndex]; if (componentGlyph.points) { transformedPoints = transformPoints(componentGlyph.points, component.dx, component.dy); glyph.points.push.apply(glyph.points, transformedPoints); } } } } return glyphs; } // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). // https://www.microsoft.com/typography/OTSPEC/loca.htm function parseLocaTable(data, start, numGlyphs, shortVersion) { var p, parseFn, glyphOffsets, glyphOffset, i; p = new Parser(data, start); parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. glyphOffsets = []; for (i = 0; i < numGlyphs + 1; i += 1) { glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4. // https://www.microsoft.com/typography/OTSPEC/cmap.htm function parseCmapTable(data, start) { var version, numTables, offset, platformId, encodingId, format, segCount, ranges, i, j, idRangeOffset, p; version = getUShort(data, start); checkArgument(version === 0, "cmap table version should be 0."); // The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 1" table. This is a Windows format. numTables = getUShort(data, start + 2); offset = -1; for (i = 0; i < numTables; i += 1) { platformId = getUShort(data, start + 4 + (i * 8)); encodingId = getUShort(data, start + 4 + (i * 8) + 2); if (platformId === 3 && (encodingId === 1 || encodingId === 0)) { offset = getULong(data, start + 4 + (i * 8) + 4); break; } } if (offset === -1) { // There is no cmap table in the font that we support, so return null. // This font will be marked as unsupported. return null; } p = new Parser(data, start + offset); format = p.parseUShort(); checkArgument(format === 4, "Only format 4 cmap tables are supported."); // Length in bytes of the sub-tables. // Skip length and language; p.skip('uShort', 2); // segCount is stored x 2. segCount = p.parseUShort() / 2; // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); ranges = []; for (i = 0; i < segCount; i += 1) { ranges[i] = { end: p.parseUShort() }; } // Skip a padding value. p.skip('uShort'); for (i = 0; i < segCount; i += 1) { ranges[i].start = p.parseUShort(); ranges[i].length = ranges[i].end - ranges[i].start; } for (i = 0; i < segCount; i += 1) { ranges[i].idDelta = p.parseShort(); } for (i = 0; i < segCount; i += 1) { idRangeOffset = p.parseUShort(); if (idRangeOffset > 0) { ranges[i].ids = []; for (j = 0; j < ranges[i].length; j += 1) { ranges[i].ids[j] = getUShort(data, start + p.relativeOffset + idRangeOffset); idRangeOffset += 2; } ranges[i].idDelta = p.parseUShort(); } } return ranges; } // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { var p, i, glyph, advanceWidth, leftSideBearing; p = new Parser(data, start); for (i = 0; i < numGlyphs; i += 1) { // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } glyph = glyphs[i]; glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } // Parse the `kern` table which contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm function parseKernTable(data, start) { var pairs, p, tableVersion, nTables, subTableVersion, nPairs, i, leftIndex, rightIndex, value; pairs = {}; p = new Parser(data, start); tableVersion = p.parseUShort(); checkArgument(tableVersion === 0, "Unsupported kern table version."); nTables = p.parseUShort(); checkArgument(nTables === 1, "Unsupported number of kern sub-tables."); subTableVersion = p.parseUShort(); checkArgument(subTableVersion === 0, "Unsupported kern sub-table version."); // Skip subTableLength, subTableCoverage p.skip('uShort', 2); nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (i = 0; i < nPairs; i += 1) { leftIndex = p.parseUShort(); rightIndex = p.parseUShort(); value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } opentype.Font = function () { this.supported = true; this.glyphs = []; }; opentype.Font.prototype.charToGlyphIndex = function (s) { var ranges, code, l, c, r; ranges = this.cmap; code = s.charCodeAt(0); l = 0; r = ranges.length - 1; while (l < r) { c = (l + r + 1) >> 1; if (code < ranges[c].start) { r = c - 1; } else { l = c; } } if (ranges[l].start <= code && code <= ranges[l].end) { return (ranges[l].idDelta + (ranges[l].ids ? ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF; } return 0; }; opentype.Font.prototype.charToGlyph = function (c) { var glyphIndex, glyph; glyphIndex = this.charToGlyphIndex(c); glyph = this.glyphs[glyphIndex]; checkArgument(glyph !== undefined, 'Could not find glyph for character ' + c + ' glyph index ' + glyphIndex); return glyph; }; opentype.Font.prototype.stringToGlyphs = function (s) { var i, c, glyphs; glyphs = []; for (i = 0; i < s.length; i += 1) { c = s[i]; glyphs.push(this.charToGlyph(c)); } return glyphs; }; opentype.Font.prototype.getKerningValue = function (leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; }; // Get a path representing the text. opentype.Font.prototype.getPath = function (text, options) { var x, y, fontSize, kerning, fontScale, glyphs, i, glyph, path, fullPath, kerningValue; if (!this.supported) { return new Path(); } options = options || {}; x = options.x || 0; y = options.y || 0; fontSize = options.fontSize || 72; kerning = options.kerning === undefined ? true : options.kerning; fontScale = 1 / this.unitsPerEm * fontSize; x /= fontScale; y /= fontScale; glyphs = this.stringToGlyphs(text); fullPath = new Path(); for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; path = opentype.glyphToPath(glyph, x, y, fontScale); fullPath.extend(path); if (glyph.advanceWidth) { x += glyph.advanceWidth; } if (kerning && i < glyphs.length - 1) { kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue; } } return fullPath; }; // Parse the OpenType file (as a buffer) and returns a Font object. opentype.parseFont = function (buffer) { var font, data, numTables, i, p, tag, offset, length, hmtxOffset, glyfOffset, locaOffset, kernOffset, magicNumber, indexToLocFormat, numGlyphs, glyf, loca, shortVersion; // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. font = new opentype.Font(); data = new DataView(buffer, 0); numTables = getUShort(data, 4); // Offset into the table records. p = 12; for (i = 0; i < numTables; i += 1) { tag = getTag(data, p); offset = getULong(data, p + 8); length = getULong(data, p + 12); switch (tag) { case 'cmap': font.cmap = parseCmapTable(data, offset); if (!font.cmap) { font.cmap = []; font.supported = false; } break; case 'head': // We're only interested in some values from the header. magicNumber = getULong(data, offset + 12); checkArgument(magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); font.unitsPerEm = getUShort(data, offset + 18); indexToLocFormat = getUShort(data, offset + 50); break; case 'hhea': font.ascender = getShort(data, offset + 4); font.descender = getShort(data, offset + 6); font.numberOfHMetrics = getUShort(data, offset + 34); break; case 'hmtx': hmtxOffset = offset; break; case 'maxp': // We're only interested in the number of glyphs. font.numGlyphs = numGlyphs = getUShort(data, offset + 4); break; case 'glyf': glyfOffset = offset; break; case 'loca': locaOffset = offset; break; case 'kern': kernOffset = offset; break; } p += 16; } if (glyfOffset && locaOffset) { shortVersion = indexToLocFormat === 0; loca = parseLocaTable(data, locaOffset, numGlyphs, shortVersion); font.glyphs = parseGlyfTable(data, glyfOffset, loca); parseHmtxTable(data, hmtxOffset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); if (kernOffset) { font.kerningPairs = parseKernTable(data, kernOffset); } else { font.kerningPairs = {}; } } else { font.supported = false; } return font; }; // Split the glyph into contours. function getContours(glyph) { var contours, currentContour, i, pt; contours = []; currentContour = []; for (i = 0; i < glyph.points.length; i += 1) { pt = glyph.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } checkArgument(currentContour.length === 0, "There are still points left in the current contour."); return contours; } // Convert the glyph to a Path we can draw on a Canvas context. opentype.glyphToPath = function (glyph, tx, ty, scale) { var path, contours, i, j, contour, pt, firstPt, prevPt, midPt, curvePt; if (tx === undefined) { tx = 0; } if (ty === undefined) { ty = 0; } if (scale === undefined) { scale = 1; } path = new Path(); if (!glyph.points) { return path; } contours = getContours(glyph); for (i = 0; i < contours.length; i += 1) { contour = contours[i]; firstPt = contour[0]; curvePt = null; for (j = 0; j < contour.length; j += 1) { pt = contour[j]; prevPt = j === 0 ? contour[contour.length - 1] : contour[j - 1]; if (j === 0) { // This is the first point of the contour. if (pt.onCurve) { path.moveTo((tx + pt.x) * scale, (ty - pt.y) * scale); curvePt = null; } else { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; curvePt = midPt; path.moveTo((tx + midPt.x) * scale, (ty - midPt.y) * scale); } } else { if (prevPt.onCurve && pt.onCurve) { // This is a straight line. path.lineTo((tx + pt.x) * scale, (ty - pt.y) * scale); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; path.quadraticCurveTo((tx + prevPt.x) * scale, (ty - prevPt.y) * scale, (tx + midPt.x) * scale, (ty - midPt.y) * scale); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. path.quadraticCurveTo((tx + curvePt.x) * scale, (ty - curvePt.y) * scale, (tx + pt.x) * scale, (ty - pt.y) * scale); curvePt = null; } else { throw new Error("Invalid state."); } } } // Connect the last and first points if (curvePt) { path.quadraticCurveTo((tx + curvePt.x) * scale, (ty - curvePt.y) * scale, (tx + firstPt.x) * scale, (ty - firstPt.y) * scale); } else { path.lineTo((tx + firstPt.x) * scale, (ty - firstPt.y) * scale); } } path.closePath(); return path; }; function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } function circle(ctx, cx, cy, r) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, false); ctx.closePath(); ctx.fill(); } opentype.drawGlyphPoints = function (ctx, glyph) { var points, i, pt; points = glyph.points; if (!points) { return; } for (i = 0; i < points.length; i += 1) { pt = points[i]; if (pt.onCurve) { ctx.fillStyle = 'blue'; } else { ctx.fillStyle = 'red'; } circle(ctx, pt.x, -pt.y, 40); } }; opentype.drawMetrics = function (ctx, glyph) { ctx.lineWidth = 10; // Draw the origin ctx.strokeStyle = 'black'; line(ctx, 0, -10000, 0, 10000); line(ctx, -10000, 0, 10000, 0); // Draw the glyph box ctx.strokeStyle = 'blue'; line(ctx, glyph.xMin, -10000, glyph.xMin, 10000); line(ctx, glyph.xMax, -10000, glyph.xMax, 10000); line(ctx, -10000, -glyph.yMin, 10000, -glyph.yMin); line(ctx, -10000, -glyph.yMax, 10000, -glyph.yMax); // Draw the advance width ctx.strokeStyle = 'green'; line(ctx, glyph.advanceWidth, -10000, glyph.advanceWidth, 10000); }; }(typeof exports === 'undefined' ? this.opentype = {} : exports));
opentype.js
// opentype.js 0.0.1 // https://github.com/nodebox/opentype.js // (c) 2013 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /*jslint bitwise: true */ /*global exports,DataView,document */ (function (exports) { 'use strict'; var opentype, dataTypes, typeOffsets; opentype = exports; // Precondition function that checks if the given predicate is true. // If not, it will log an error message to the console. function checkArgument(predicate, message) { if (!predicate) { throw new Error(message); } } function Path() { this.commands = []; this.fill = 'black'; this.stroke = null; this.strokeWidth = 1; } Path.prototype.moveTo = function (x, y) { this.commands.push({type: 'M', x: x, y: y}); }; Path.prototype.lineTo = function (x, y) { this.commands.push({type: 'L', x: x, y: y}); }; Path.prototype.curveTo = Path.prototype.bezierCurveTo = function (x1, y1, x2, y2, x, y) { this.commands.push({type: 'C', x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y}); }; Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function (x1, y1, x, y) { this.commands.push({type: 'Q', x1: x1, y1: y1, x: x, y: y}); }; Path.prototype.close = Path.prototype.closePath = function () { this.commands.push({type: 'Z'}); }; Path.prototype.extend = function (pathOrCommands) { if (pathOrCommands.commands) { pathOrCommands = pathOrCommands.commands; } this.commands.push.apply(this.commands, pathOrCommands); }; // Draw the path to a 2D context. Path.prototype.draw = function (ctx) { var i, cmd; ctx.beginPath(); for (i = 0; i < this.commands.length; i += 1) { cmd = this.commands[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; Path.prototype.drawPoints = function (ctx) { var i, cmd, blueCircles, redCircles; blueCircles = []; redCircles = []; for (i = 0; i < this.commands.length; i += 1) { cmd = this.commands[i]; if (cmd.type === 'M') { blueCircles.push(cmd); } else if (cmd.type === 'L') { blueCircles.push(cmd); } else if (cmd.type === 'C') { redCircles.push(cmd); } else if (cmd.type === 'Q') { redCircles.push(cmd); } } function drawCircles(l) { var j, PI_SQ = Math.PI * 2; ctx.beginPath(); for (j = 0; j < l.length; j += 1) { ctx.moveTo(l[j].x, l[j].y); ctx.arc(l[j].x, l[j].y, 2, 0, PI_SQ, false); } ctx.closePath(); ctx.fill(); } ctx.fillStyle = 'blue'; drawCircles(blueCircles); ctx.fillStyle = 'red'; drawCircles(redCircles); }; function getByte(dataView, offset) { return dataView.getUint8(offset); } function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } function getShort(dataView, offset) { return dataView.getInt16(offset, false); } function getULong(dataView, offset) { return dataView.getUint32(offset, false); } function getFixed(dataView, offset) { return -1; } function getLongDateTime(dataView, offset) { var v1, v2; v1 = dataView.getUint32(offset, false); v2 = dataView.getUint32(offset + 1, false); return [v1, v2]; } function getTag(dataView, offset) { var tag = '', i; for (i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(dataView.getInt8(i)); } return tag; } dataTypes = { byte: getByte, uShort: getUShort, short: getShort, uLong: getULong, fixed: getFixed, longDateTime: getLongDateTime, tag: getTag }; typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; // A stateful parser that changes the offset whenever a value is retrieved. function Parser(dataView, offset) { this.dataView = dataView; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parse = function (type) { var parseFn, v; parseFn = dataTypes[type]; v = parseFn(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += typeOffsets[type]; return v; }; Parser.prototype.parseByte = function () { var v = getByte(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseUShort = function () { var v = getUShort(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseShort = function () { var v = getShort(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function () { var v = getULong(this.dataView, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.skip = function (type, amount) { if (amount === undefined) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; // Return true if the value at the given bit index is set. function isBitSet(b, bitIndex) { return ((b >> bitIndex) & 1) === 1; } // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBit, sameBit) { var v; if (isBitSet(flag, shortVectorBit)) { // The coordinate is 1 byte long. v = p.parse('byte'); // The `same` bit is re-used for short values to signify the sign of the value. if (!isBitSet(flag, sameBit)) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if (isBitSet(flag, sameBit)) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parse('short'); } } return v; } // Parse an OpenType glyph (described in the glyf table). // Due to the complexity of the parsing we can't define the glyf table declaratively. // The offset is the absolute byte offset of the glyph: the base of the glyph table + the relative offset of the glyph. // http://www.microsoft.com/typography/otspec/glyf.htm function parseGlyph(data, start, index) { var p, glyph, flag, i, j, flags, endPointIndices, numberOfCoordinates, repeatCount, points, point, px, py, component, moreComponents, arg1, arg2, scale, xScale, yScale, scale01, scale10; p = new Parser(data, start); glyph = {}; glyph.index = index; glyph.numberOfContours = p.parseShort(); glyph.xMin = p.parseShort(); glyph.yMin = p.parseShort(); glyph.xMax = p.parseShort(); glyph.yMax = p.parseShort(); if (glyph.numberOfContours > 0) { // This glyph is not a composite. endPointIndices = glyph.endPointIndices = []; for (i = 0; i < glyph.numberOfContours; i += 1) { endPointIndices.push(p.parseUShort()); } glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (i = 0; i < numberOfCoordinates; i += 1) { flag = p.parseByte(); flags.push(flag); // If bit 3 is set, we repeat this flag n times, where n is the next byte. if (isBitSet(flag, 3)) { repeatCount = p.parseByte(); for (j = 0; j < repeatCount; j += 1) { flags.push(flag); i += 1; } } } checkArgument(flags.length === numberOfCoordinates, 'Bad flags.'); if (endPointIndices.length > 0) { points = []; // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if (numberOfCoordinates > 0) { for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = {}; point.onCurve = isBitSet(flag, 0); point.lastPointOfContour = endPointIndices.indexOf(i) >= 0; points.push(point); } px = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.x = parseGlyphCoordinate(p, flag, px, 1, 4); px = point.x; } py = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.y = parseGlyphCoordinate(p, flag, py, 2, 5); py = point.y; } } glyph.points = points; } else { glyph.points = []; } } else if (glyph.numberOfContours === 0) { glyph.points = []; } else { glyph.isComposite = true; glyph.points = []; glyph.components = []; moreComponents = true; while (moreComponents) { component = {}; flags = p.parseUShort(); component.glyphIndex = p.parseUShort(); if (isBitSet(flags, 0)) { // The arguments are words arg1 = p.parseShort(); arg2 = p.parseShort(); component.dx = arg1; component.dy = arg2; } else { // The arguments are bytes arg1 = p.parseByte(); arg2 = p.parseByte(); component.dx = arg1; component.dy = arg2; } if (isBitSet(flags, 3)) { // We have a scale // TODO parse in 16-bit signed fixed number with the low 14 bits of fraction (2.14). scale = p.parseShort(); } else if (isBitSet(flags, 6)) { // We have an X / Y scale xScale = p.parseShort(); yScale = p.parseShort(); } else if (isBitSet(flags, 7)) { // We have a 2x2 transformation xScale = p.parseShort(); scale01 = p.parseShort(); scale10 = p.parseShort(); yScale = p.parseShort(); } glyph.components.push(component); moreComponents = isBitSet(flags, 5); } } return glyph; } // Transform an array of points and return a new array. function transformPoints(points, dx, dy) { var newPoints, i, pt, newPt; newPoints = []; for (i = 0; i < points.length; i += 1) { pt = points[i]; newPt = { x: pt.x + dx, y: pt.y + dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } // Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data, start, loca) { var glyphs, i, j, offset, nextOffset, glyph, component, componentGlyph, transformedPoints; glyphs = []; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { offset = loca[i]; nextOffset = loca[i + 1]; if (offset !== nextOffset) { glyphs.push(parseGlyph(data, start + offset, i)); } else { glyphs.push({index: i, numberOfContours: 0, xMin: 0, xMax: 0, yMin: 0, yMax: 0}); } } // Go over the glyphs again, resolving the composite glyphs. for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; if (glyph.isComposite) { for (j = 0; j < glyph.components.length; j += 1) { component = glyph.components[j]; componentGlyph = glyphs[component.glyphIndex]; if (componentGlyph.points) { transformedPoints = transformPoints(componentGlyph.points, component.dx, component.dy); glyph.points.push.apply(glyph.points, transformedPoints); } } } } return glyphs; } // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). // https://www.microsoft.com/typography/OTSPEC/loca.htm function parseLocaTable(data, start, numGlyphs, shortVersion) { var p, parseFn, glyphOffsets, glyphOffset, i; p = new Parser(data, start); parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. glyphOffsets = []; for (i = 0; i < numGlyphs + 1; i += 1) { glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4. // https://www.microsoft.com/typography/OTSPEC/cmap.htm function parseCmapTable(data, start) { var version, numTables, offset, platformId, encodingId, format, segCount, ranges, i, j, idRangeOffset, p; version = getUShort(data, start); checkArgument(version === 0, "cmap table version should be 0."); // The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 1" table. This is a Windows format. numTables = getUShort(data, start + 2); offset = -1; for (i = 0; i < numTables; i += 1) { platformId = getUShort(data, start + 4 + (i * 8)); encodingId = getUShort(data, start + 4 + (i * 8) + 2); if (platformId === 3 && (encodingId === 1 || encodingId === 0)) { offset = getULong(data, start + 4 + (i * 8) + 4); break; } } if (offset === -1) { throw new Error("Could not find supported cmap encoding."); } p = new Parser(data, start + offset); format = p.parseUShort(); checkArgument(format === 4, "Only format 4 cmap tables are supported."); // Length in bytes of the sub-tables. // Skip length and language; p.skip('uShort', 2); // segCount is stored x 2. segCount = p.parseUShort() / 2; // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); ranges = []; for (i = 0; i < segCount; i += 1) { ranges[i] = { end: p.parseUShort() }; } // Skip a padding value. p.skip('uShort'); for (i = 0; i < segCount; i += 1) { ranges[i].start = p.parseUShort(); ranges[i].length = ranges[i].end - ranges[i].start; } for (i = 0; i < segCount; i += 1) { ranges[i].idDelta = p.parseShort(); } for (i = 0; i < segCount; i += 1) { idRangeOffset = p.parseUShort(); if (idRangeOffset > 0) { ranges[i].ids = []; for (j = 0; j < ranges[i].length; j += 1) { ranges[i].ids[j] = getUShort(data, start + p.relativeOffset + idRangeOffset); idRangeOffset += 2; } ranges[i].idDelta = p.parseUShort(); } } return ranges; } // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { var p, i, glyph, advanceWidth, leftSideBearing; p = new Parser(data, start); for (i = 0; i < numGlyphs; i += 1) { // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } glyph = glyphs[i]; glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } // Parse the `kern` table which contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm function parseKernTable(data, start) { var pairs, p, tableVersion, nTables, subTableVersion, nPairs, i, leftIndex, rightIndex, value; pairs = {}; p = new Parser(data, start); tableVersion = p.parseUShort(); checkArgument(tableVersion === 0, "Unsupported kern table version."); nTables = p.parseUShort(); checkArgument(nTables === 1, "Unsupported number of kern sub-tables."); subTableVersion = p.parseUShort(); checkArgument(subTableVersion === 0, "Unsupported kern sub-table version."); // Skip subTableLength, subTableCoverage p.skip('uShort', 2); nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (i = 0; i < nPairs; i += 1) { leftIndex = p.parseUShort(); rightIndex = p.parseUShort(); value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } opentype.Font = function () { this.supported = true; this.glyphs = []; }; opentype.Font.prototype.charToGlyphIndex = function (s) { var ranges, code, l, c, r; ranges = this.cmap; code = s.charCodeAt(0); l = 0; r = ranges.length - 1; while (l < r) { c = (l + r + 1) >> 1; if (code < ranges[c].start) { r = c - 1; } else { l = c; } } if (ranges[l].start <= code && code <= ranges[l].end) { return (ranges[l].idDelta + (ranges[l].ids ? ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF; } return 0; }; opentype.Font.prototype.charToGlyph = function (c) { var glyphIndex, glyph; glyphIndex = this.charToGlyphIndex(c); glyph = this.glyphs[glyphIndex]; checkArgument(glyph !== undefined, 'Could not find glyph for character ' + c + ' glyph index ' + glyphIndex); return glyph; }; opentype.Font.prototype.stringToGlyphs = function (s) { var i, c, glyphs; glyphs = []; for (i = 0; i < s.length; i += 1) { c = s[i]; glyphs.push(this.charToGlyph(c)); } return glyphs; }; opentype.Font.prototype.getKerningValue = function (leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; }; // Get a path representing the text. opentype.Font.prototype.getPath = function (text, options) { var x, y, fontSize, kerning, fontScale, glyphs, i, glyph, path, fullPath, kerningValue; if (!this.supported) { return new Path(); } options = options || {}; x = options.x || 0; y = options.y || 0; fontSize = options.fontSize || 72; kerning = options.kerning === undefined ? true : options.kerning; fontScale = 1 / this.unitsPerEm * fontSize; x /= fontScale; y /= fontScale; glyphs = this.stringToGlyphs(text); fullPath = new Path(); for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; path = opentype.glyphToPath(glyph, x, y, fontScale); fullPath.extend(path); if (glyph.advanceWidth) { x += glyph.advanceWidth; } if (kerning && i < glyphs.length - 1) { kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue; } } return fullPath; }; // Parse the OpenType file (as a buffer) and returns a Font object. opentype.parseFont = function (buffer) { var font, data, numTables, i, p, tag, offset, length, hmtxOffset, glyfOffset, locaOffset, kernOffset, magicNumber, indexToLocFormat, numGlyphs, glyf, loca, shortVersion; // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. font = new opentype.Font(); data = new DataView(buffer, 0); numTables = getUShort(data, 4); // Offset into the table records. p = 12; for (i = 0; i < numTables; i += 1) { tag = getTag(data, p); offset = getULong(data, p + 8); length = getULong(data, p + 12); switch (tag) { case 'cmap': font.cmap = parseCmapTable(data, offset); break; case 'head': // We're only interested in some values from the header. magicNumber = getULong(data, offset + 12); checkArgument(magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); font.unitsPerEm = getUShort(data, offset + 18); indexToLocFormat = getUShort(data, offset + 50); break; case 'hhea': font.ascender = getShort(data, offset + 4); font.descender = getShort(data, offset + 6); font.numberOfHMetrics = getUShort(data, offset + 34); break; case 'hmtx': hmtxOffset = offset; break; case 'maxp': // We're only interested in the number of glyphs. font.numGlyphs = numGlyphs = getUShort(data, offset + 4); break; case 'glyf': glyfOffset = offset; break; case 'loca': locaOffset = offset; break; case 'kern': kernOffset = offset; break; } p += 16; } if (glyfOffset && locaOffset) { shortVersion = indexToLocFormat === 0; loca = parseLocaTable(data, locaOffset, numGlyphs, shortVersion); font.glyphs = parseGlyfTable(data, glyfOffset, loca); parseHmtxTable(data, hmtxOffset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); if (kernOffset) { font.kerningPairs = parseKernTable(data, kernOffset); } else { font.kerningPairs = {}; } } else { font.supported = false; } return font; }; // Split the glyph into contours. function getContours(glyph) { var contours, currentContour, i, pt; contours = []; currentContour = []; for (i = 0; i < glyph.points.length; i += 1) { pt = glyph.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } checkArgument(currentContour.length === 0, "There are still points left in the current contour."); return contours; } // Convert the glyph to a Path we can draw on a Canvas context. opentype.glyphToPath = function (glyph, tx, ty, scale) { var path, contours, i, j, contour, pt, firstPt, prevPt, midPt, curvePt; if (tx === undefined) { tx = 0; } if (ty === undefined) { ty = 0; } if (scale === undefined) { scale = 1; } path = new Path(); if (!glyph.points) { return path; } contours = getContours(glyph); for (i = 0; i < contours.length; i += 1) { contour = contours[i]; firstPt = contour[0]; curvePt = null; for (j = 0; j < contour.length; j += 1) { pt = contour[j]; prevPt = j === 0 ? contour[contour.length - 1] : contour[j - 1]; if (j === 0) { // This is the first point of the contour. if (pt.onCurve) { path.moveTo((tx + pt.x) * scale, (ty - pt.y) * scale); curvePt = null; } else { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; curvePt = midPt; path.moveTo((tx + midPt.x) * scale, (ty - midPt.y) * scale); } } else { if (prevPt.onCurve && pt.onCurve) { // This is a straight line. path.lineTo((tx + pt.x) * scale, (ty - pt.y) * scale); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; path.quadraticCurveTo((tx + prevPt.x) * scale, (ty - prevPt.y) * scale, (tx + midPt.x) * scale, (ty - midPt.y) * scale); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. path.quadraticCurveTo((tx + curvePt.x) * scale, (ty - curvePt.y) * scale, (tx + pt.x) * scale, (ty - pt.y) * scale); curvePt = null; } else { throw new Error("Invalid state."); } } } // Connect the last and first points if (curvePt) { path.quadraticCurveTo((tx + curvePt.x) * scale, (ty - curvePt.y) * scale, (tx + firstPt.x) * scale, (ty - firstPt.y) * scale); } else { path.lineTo((tx + firstPt.x) * scale, (ty - firstPt.y) * scale); } } path.closePath(); return path; }; function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } function circle(ctx, cx, cy, r) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, false); ctx.closePath(); ctx.fill(); } opentype.drawGlyphPoints = function (ctx, glyph) { var points, i, pt; points = glyph.points; if (!points) { return; } for (i = 0; i < points.length; i += 1) { pt = points[i]; if (pt.onCurve) { ctx.fillStyle = 'blue'; } else { ctx.fillStyle = 'red'; } circle(ctx, pt.x, -pt.y, 40); } }; opentype.drawMetrics = function (ctx, glyph) { ctx.lineWidth = 10; // Draw the origin ctx.strokeStyle = 'black'; line(ctx, 0, -10000, 0, 10000); line(ctx, -10000, 0, 10000, 0); // Draw the glyph box ctx.strokeStyle = 'blue'; line(ctx, glyph.xMin, -10000, glyph.xMin, 10000); line(ctx, glyph.xMax, -10000, glyph.xMax, 10000); line(ctx, -10000, -glyph.yMin, 10000, -glyph.yMin); line(ctx, -10000, -glyph.yMax, 10000, -glyph.yMax); // Draw the advance width ctx.strokeStyle = 'green'; line(ctx, glyph.advanceWidth, -10000, glyph.advanceWidth, 10000); }; }(typeof exports === 'undefined' ? this.opentype = {} : exports));
Fonts with unsupported cmap tables no longer crash.
opentype.js
Fonts with unsupported cmap tables no longer crash.
<ide><path>pentype.js <ide> } <ide> } <ide> if (offset === -1) { <del> throw new Error("Could not find supported cmap encoding."); <add> // There is no cmap table in the font that we support, so return null. <add> // This font will be marked as unsupported. <add> return null; <ide> } <ide> <ide> p = new Parser(data, start + offset); <ide> switch (tag) { <ide> case 'cmap': <ide> font.cmap = parseCmapTable(data, offset); <add> if (!font.cmap) { <add> font.cmap = []; <add> font.supported = false; <add> } <ide> break; <ide> case 'head': <ide> // We're only interested in some values from the header.
Java
apache-2.0
be03d10e20a0c3b6a09377b20d7b95d7a7ddfeca
0
brandt/GridSphere,brandt/GridSphere
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import org.gridlab.gridsphere.services.core.tracker.TrackerService; import org.gridlab.gridsphere.services.core.tracker.impl.TrackerServiceImpl; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.net.SocketException; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private static TrackerService trackerService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); //SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); factory.init(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); trackerService = (TrackerService) factory.createPortletService(TrackerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); String trackme = req.getParameter(TrackerService.TRACK_PARAM); if (trackme != null) { trackerService.trackURL(trackme, req.getHeader("user-agent"), portletReq.getUser().getUserName()); String url = req.getParameter(TrackerService.REDIRECT_URL); if (url != null) { System.err.println("redirect: " + url); res.sendRedirect(url); } } checkUserHasCookie(event); // Used for TCK tests if (isTCK) setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); // Used for TCK tests if (isTCK) setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf("#"); if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf("#"); if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); try { User user = loginService.login(req); setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (SocketException e) { log.error("Caught SocketException: " + e.getMessage()); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { System.err.println("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
src/org/gridlab/gridsphere/servlets/GridSphereServlet.java
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import org.gridlab.gridsphere.services.core.tracker.TrackerService; import org.gridlab.gridsphere.services.core.tracker.impl.TrackerServiceImpl; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.net.SocketException; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private static TrackerService trackerService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); //SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); factory.init(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); trackerService = (TrackerService) factory.createPortletService(TrackerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); String trackme = req.getParameter(TrackerService.TRACK_PARAM); if (trackme != null) { trackerService.trackURL(trackme, req.getHeader("user-agent"), portletReq.getUser().getID()); String url = req.getParameter(TrackerService.REDIRECT_URL); if (url != null) { System.err.println("redirect: " + url); res.sendRedirect(url); } } checkUserHasCookie(event); // Used for TCK tests if (isTCK) setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); // Used for TCK tests if (isTCK) setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf("#"); if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf("#"); if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); try { User user = loginService.login(req); setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (SocketException e) { log.error("Caught SocketException: " + e.getMessage()); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { System.err.println("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
track by user name not useoid git-svn-id: 616481d960d639df1c769687dde8737486ca2a9a@4149 9c99c85f-4d0c-0410-8460-a9a1c48a3a7f
src/org/gridlab/gridsphere/servlets/GridSphereServlet.java
track by user name not useoid
<ide><path>rc/org/gridlab/gridsphere/servlets/GridSphereServlet.java <ide> <ide> String trackme = req.getParameter(TrackerService.TRACK_PARAM); <ide> if (trackme != null) { <del> trackerService.trackURL(trackme, req.getHeader("user-agent"), portletReq.getUser().getID()); <add> trackerService.trackURL(trackme, req.getHeader("user-agent"), portletReq.getUser().getUserName()); <ide> String url = req.getParameter(TrackerService.REDIRECT_URL); <ide> if (url != null) { <ide> System.err.println("redirect: " + url);
JavaScript
bsd-3-clause
91d73acaec99033d7b127d2852a9dd5c3e038439
0
django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo
/* * Leonardo resource loader */ var leonardo = function(leonardo) { leonardo.fn = leonardo.fn || {}; /** * Add JS / CSS resource to DOM, if not exists * @example loadResource({src:'/my.js',async:true,defer:true}) <br> * loadResource("/my.js") or arrays of them * loadResource(["/lol.js","/lol2.js",{src:"/lol2",async:true}]) * loadResource("/lol.css",{src:"/megalol.css"}) * USE ONLY ABSOLUTE PATHS */ leonardo.fn.loadResource = function (resources){ var addScriptFn = function(script){ var resources = document.getElementsByTagName('script'),found=false; for(var i=0;i<resources.length;i++){ var fullSrc = (script.src.indexOf("://") > -1)?script.src:window.location.protocol+"//"+script.src; if(resources[i].src===fullSrc){ found=true; break; } } if(!found){ var domScript = document.createElement('script'); domScript.type = "text/javascript"; if(script.callback){ if(typeof script.callback === 'function'){ domScript.onload=script.callback; }else{ domScript.onload=window[script.callback]; } } domScript.src = script.src; domScript.async = script.async && script.async==true; domScript.defer = script.defer && script.defer==true; resources[0].parentNode.insertBefore(domScript, resources[0]); } }, addStyleFn = function(style){ var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = style.src; document.getElementsByTagName("head")[0].appendChild(link); }, addElement = function(elem){ var lastDot = elem.src.lastIndexOf("."), resExt = elem.src.substring(lastDot); if(resExt === '.css'){ addStyleFn(elem); }else{ addScriptFn(elem); } }; if(resources instanceof Array){ for(var i=0;i<resources.length;i++){ if(typeof resources[i] === 'object' && resources[i].hasOwnProperty("src")){ addElement(resources[i]) }else if(typeof resources[i] === 'string'){ addElement({src:resources[i]}); }else{ console.log("Resource #"+i+" is invalid!"); } } }else{ if(typeof resources === 'object' && resources.hasOwnProperty("src")){ addElement(resources); }else if(typeof resources === 'string'){ addElement({src:resources}); }else{ console.log("Resource is invalid!"); } } }; // window temponary fallback window.loadResource = leonardo.fn.loadResource; return leonardo; }(leonardo || {});
leonardo/static/js/lib/loader.js
/** * Add JS / CSS resource to DOM, if not exists * @example loadResource({src:'/my.js',async:true,defer:true}) <br> * loadResource("/my.js") or arrays of them * loadResource(["/lol.js","/lol2.js",{src:"/lol2",async:true}]) * loadResource("/lol.css",{src:"/megalol.css"}) * USE ONLY ABSOLUTE PATHS */ function loadResource(resources){ var addScriptFn = function(script){ var resources = document.getElementsByTagName('script'),found=false; for(var i=0;i<resources.length;i++){ var fullSrc = (script.src.indexOf("://") > -1)?script.src:window.location.protocol+"//"+script.src; if(resources[i].src===fullSrc){ found=true; break; } } if(!found){ var domScript = document.createElement('script'); domScript.type = "text/javascript"; if(script.callback){ if(typeof script.callback === 'function'){ domScript.onload=script.callback; }else{ domScript.onload=window[script.callback]; } } domScript.src = script.src; domScript.async = script.async && script.async==true; domScript.defer = script.defer && script.defer==true; resources[0].parentNode.insertBefore(domScript, resources[0]); } }, addStyleFn = function(style){ var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = style.src; document.getElementsByTagName("head")[0].appendChild(link); }, addElement = function(elem){ var lastDot = elem.src.lastIndexOf("."), resExt = elem.src.substring(lastDot); if(resExt === '.css'){ addStyleFn(elem); }else{ addScriptFn(elem); } }; if(resources instanceof Array){ for(var i=0;i<resources.length;i++){ if(typeof resources[i] === 'object' && resources[i].hasOwnProperty("src")){ addElement(resources[i]) }else if(typeof resources[i] === 'string'){ addElement({src:resources[i]}); }else{ console.log("Resource #"+i+" is invalid!"); } } }else{ if(typeof resources === 'object' && resources.hasOwnProperty("src")){ addElement(resources); }else if(typeof resources === 'string'){ addElement({src:resources}); }else{ console.log("Resource is invalid!"); } } }
JS Load resource function location changed due to new convensions (with fallback).
leonardo/static/js/lib/loader.js
JS Load resource function location changed due to new convensions (with fallback).
<ide><path>eonardo/static/js/lib/loader.js <del>/** <del> * Add JS / CSS resource to DOM, if not exists <del> * @example loadResource({src:'/my.js',async:true,defer:true}) <br> <del> * loadResource("/my.js") or arrays of them <del> * loadResource(["/lol.js","/lol2.js",{src:"/lol2",async:true}]) <del> * loadResource("/lol.css",{src:"/megalol.css"}) <del> * USE ONLY ABSOLUTE PATHS <add>/* <add> * Leonardo resource loader <ide> */ <del>function loadResource(resources){ <del> var addScriptFn = function(script){ <del> var resources = document.getElementsByTagName('script'),found=false; <del> for(var i=0;i<resources.length;i++){ <del> var fullSrc = (script.src.indexOf("://") > -1)?script.src:window.location.protocol+"//"+script.src; <del> if(resources[i].src===fullSrc){ <del> found=true; <del> break; <add>var leonardo = function(leonardo) { <add> leonardo.fn = leonardo.fn || {}; <add> /** <add> * Add JS / CSS resource to DOM, if not exists <add> * @example loadResource({src:'/my.js',async:true,defer:true}) <br> <add> * loadResource("/my.js") or arrays of them <add> * loadResource(["/lol.js","/lol2.js",{src:"/lol2",async:true}]) <add> * loadResource("/lol.css",{src:"/megalol.css"}) <add> * USE ONLY ABSOLUTE PATHS <add> */ <add> leonardo.fn.loadResource = function (resources){ <add> var addScriptFn = function(script){ <add> var resources = document.getElementsByTagName('script'),found=false; <add> for(var i=0;i<resources.length;i++){ <add> var fullSrc = (script.src.indexOf("://") > -1)?script.src:window.location.protocol+"//"+script.src; <add> if(resources[i].src===fullSrc){ <add> found=true; <add> break; <add> } <add> } <add> if(!found){ <add> var domScript = document.createElement('script'); <add> domScript.type = "text/javascript"; <add> if(script.callback){ <add> if(typeof script.callback === 'function'){ <add> domScript.onload=script.callback; <add> }else{ <add> domScript.onload=window[script.callback]; <add> } <add> } <add> domScript.src = script.src; <add> domScript.async = script.async && script.async==true; <add> domScript.defer = script.defer && script.defer==true; <add> resources[0].parentNode.insertBefore(domScript, resources[0]); <add> } <add> }, addStyleFn = function(style){ <add> var link = document.createElement("link"); <add> link.type = "text/css"; <add> link.rel = "stylesheet"; <add> link.href = style.src; <add> document.getElementsByTagName("head")[0].appendChild(link); <add> }, addElement = function(elem){ <add> var lastDot = elem.src.lastIndexOf("."), resExt = elem.src.substring(lastDot); <add> if(resExt === '.css'){ <add> addStyleFn(elem); <add> }else{ <add> addScriptFn(elem); <add> } <add> }; <add> if(resources instanceof Array){ <add> for(var i=0;i<resources.length;i++){ <add> if(typeof resources[i] === 'object' && resources[i].hasOwnProperty("src")){ <add> addElement(resources[i]) <add> }else if(typeof resources[i] === 'string'){ <add> addElement({src:resources[i]}); <add> }else{ <add> console.log("Resource #"+i+" is invalid!"); <add> } <add> } <add> }else{ <add> if(typeof resources === 'object' && resources.hasOwnProperty("src")){ <add> addElement(resources); <add> }else if(typeof resources === 'string'){ <add> addElement({src:resources}); <add> }else{ <add> console.log("Resource is invalid!"); <ide> } <ide> } <del> if(!found){ <del> var domScript = document.createElement('script'); <del> domScript.type = "text/javascript"; <del> if(script.callback){ <del> if(typeof script.callback === 'function'){ <del> domScript.onload=script.callback; <del> }else{ <del> domScript.onload=window[script.callback]; <del> } <del> } <del> domScript.src = script.src; <del> domScript.async = script.async && script.async==true; <del> domScript.defer = script.defer && script.defer==true; <del> resources[0].parentNode.insertBefore(domScript, resources[0]); <del> } <del> }, addStyleFn = function(style){ <del> var link = document.createElement("link"); <del> link.type = "text/css"; <del> link.rel = "stylesheet"; <del> link.href = style.src; <del> document.getElementsByTagName("head")[0].appendChild(link); <del> }, addElement = function(elem){ <del> var lastDot = elem.src.lastIndexOf("."), resExt = elem.src.substring(lastDot); <del> if(resExt === '.css'){ <del> addStyleFn(elem); <del> }else{ <del> addScriptFn(elem); <del> } <ide> }; <del> if(resources instanceof Array){ <del> for(var i=0;i<resources.length;i++){ <del> if(typeof resources[i] === 'object' && resources[i].hasOwnProperty("src")){ <del> addElement(resources[i]) <del> }else if(typeof resources[i] === 'string'){ <del> addElement({src:resources[i]}); <del> }else{ <del> console.log("Resource #"+i+" is invalid!"); <del> } <del> } <del> }else{ <del> if(typeof resources === 'object' && resources.hasOwnProperty("src")){ <del> addElement(resources); <del> }else if(typeof resources === 'string'){ <del> addElement({src:resources}); <del> }else{ <del> console.log("Resource is invalid!"); <del> } <del> } <del>} <add> <add> // window temponary fallback <add> window.loadResource = leonardo.fn.loadResource; <add> return leonardo; <add>}(leonardo || {});
Java
apache-2.0
895fa11ea6204f06d75306b6457170751affc7cc
0
deveth0/bitcointrader,deveth0/bitcointrader,deveth0/bitcointrader
//$URL$ //$Id$ package de.dev.eth0.bitcointrader.ui.fragments; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import de.dev.eth0.bitcointrader.BitcoinTraderApplication; import de.dev.eth0.bitcointrader.Constants; import de.dev.eth0.bitcointrader.R; import de.dev.eth0.bitcointrader.service.ExchangeService; import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity; import de.dev.eth0.bitcointrader.ui.views.CurrencyAmountView; import de.schildbach.wallet.ui.HelpDialogFragment; import org.joda.money.BigMoney; /** * * @author Alexander Muthmann */ public class TrailingStopLossFragment extends AbstractBitcoinTraderFragment { private final static String TAG = TrailingStopLossFragment.class.getSimpleName(); private EditText percentageTextView; private EditText priceTextView; private EditText updatesTextView; private BitcoinTraderApplication application; private AbstractBitcoinTraderActivity activity; private Button viewGo; private Button viewCancel; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = (AbstractBitcoinTraderActivity) activity; this.application = (BitcoinTraderApplication) activity.getApplication(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.trailingstoploss_options, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bitcointrader_options_help: HelpDialogFragment.page(activity.getSupportFragmentManager(), "help_trailing_stop_loss"); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.trailing_stop_loss_fragment, container); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { percentageTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_percentage_text); priceTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_price_text); updatesTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_updates_text); CurrencyAmountView priceView = (CurrencyAmountView) view.findViewById(R.id.trailing_stop_dialog_price); if (getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { priceView.setCurrencyCode(getExchangeService().getCurrency()); } CurrencyAmountView percentageView = (CurrencyAmountView) view.findViewById(R.id.trailing_stop_dialog_percentage); percentageView.setCurrencyCode("%"); viewGo = (Button) view.findViewById(R.id.trailing_stop_loss_perform); viewGo.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); Float threashold = Float.parseFloat(percentageTextView.getEditableText().toString()); String price = priceTextView.getEditableText().toString(); String updates = updatesTextView.getEditableText().toString(); int numberUpdates = 1; try { numberUpdates = Integer.parseInt(updates); } catch (NumberFormatException nfe) { } if (!TextUtils.isEmpty(price)) { String currency = "USD"; if(getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { currency = getExchangeService().getCurrency(); } BigMoney priceCurrency = BigMoney.parse(currency + " 0" + price.toString()); SharedPreferences.Editor editor = prefs.edit(); editor.putFloat(Constants.PREFS_TRAILING_STOP_THREASHOLD, threashold); editor.putString(Constants.PREFS_TRAILING_STOP_VALUE, priceCurrency.getAmount().toString()); editor.putInt(Constants.PREFS_TRAILING_STOP_NUMBER_UPDATES, numberUpdates); editor.apply(); Toast.makeText(getActivity(), R.string.trailing_stop_loss_submitted, Toast.LENGTH_LONG).show(); activity.setResult(Activity.RESULT_OK); activity.finish(); } } catch (Exception ex) { Log.w(TAG, ex); Toast.makeText(getActivity(), R.string.trailing_stop_loss_wrong_input, Toast.LENGTH_LONG).show(); } } }); viewCancel = (Button) view.findViewById(R.id.trailing_stop_loss_cancel); viewCancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { activity.setResult(Activity.RESULT_CANCELED); activity.finish(); } }); } }
BitcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossFragment.java
//$URL$ //$Id$ package de.dev.eth0.bitcointrader.ui.fragments; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import de.dev.eth0.bitcointrader.BitcoinTraderApplication; import de.dev.eth0.bitcointrader.Constants; import de.dev.eth0.bitcointrader.R; import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity; import de.dev.eth0.bitcointrader.ui.views.CurrencyAmountView; import de.schildbach.wallet.ui.HelpDialogFragment; import org.joda.money.BigMoney; /** * * @author Alexander Muthmann */ public class TrailingStopLossFragment extends AbstractBitcoinTraderFragment { private final static String TAG = TrailingStopLossFragment.class.getSimpleName(); private EditText percentageTextView; private EditText priceTextView; private EditText updatesTextView; private BitcoinTraderApplication application; private AbstractBitcoinTraderActivity activity; private Button viewGo; private Button viewCancel; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = (AbstractBitcoinTraderActivity)activity; this.application = (BitcoinTraderApplication)activity.getApplication(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.trailingstoploss_options, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bitcointrader_options_help: HelpDialogFragment.page(activity.getSupportFragmentManager(), "help_trailing_stop_loss"); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.trailing_stop_loss_fragment, container); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { final String currency = getExchangeService().getCurrency(); percentageTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_percentage_text); priceTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_price_text); updatesTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_updates_text); CurrencyAmountView priceView = (CurrencyAmountView)view.findViewById(R.id.trailing_stop_dialog_price); priceView.setCurrencyCode(currency); CurrencyAmountView percentageView = (CurrencyAmountView)view.findViewById(R.id.trailing_stop_dialog_percentage); percentageView.setCurrencyCode("%"); viewGo = (Button)view.findViewById(R.id.trailing_stop_loss_perform); viewGo.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); Float threashold = Float.parseFloat(percentageTextView.getEditableText().toString()); String price = priceTextView.getEditableText().toString(); String updates = updatesTextView.getEditableText().toString(); int numberUpdates = 1; try { numberUpdates = Integer.parseInt(updates); } catch (NumberFormatException nfe) { } if (!TextUtils.isEmpty(price)) { BigMoney priceCurrency = BigMoney.parse(currency + " 0" + price.toString()); SharedPreferences.Editor editor = prefs.edit(); editor.putFloat(Constants.PREFS_TRAILING_STOP_THREASHOLD, threashold); editor.putString(Constants.PREFS_TRAILING_STOP_VALUE, priceCurrency.getAmount().toString()); editor.putInt(Constants.PREFS_TRAILING_STOP_NUMBER_UPDATES, numberUpdates); editor.apply(); Toast.makeText(getActivity(), R.string.trailing_stop_loss_submitted, Toast.LENGTH_LONG).show(); activity.setResult(Activity.RESULT_OK); activity.finish(); } } catch (Exception ex) { Log.w(TAG, ex); Toast.makeText(getActivity(), R.string.trailing_stop_loss_wrong_input, Toast.LENGTH_LONG).show(); } } }); viewCancel = (Button)view.findViewById(R.id.trailing_stop_loss_cancel); viewCancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { activity.setResult(Activity.RESULT_CANCELED); activity.finish(); } }); } }
Bitcointrader: fixes #129 (NPE) git-svn-id: a355d1b694e879546a774084536e9dc3bacb52b5@294 46fdfbd1-27fd-a4d1-f970-16196c59cddc
BitcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossFragment.java
Bitcointrader: fixes #129 (NPE)
<ide><path>itcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossFragment.java <ide> import de.dev.eth0.bitcointrader.BitcoinTraderApplication; <ide> import de.dev.eth0.bitcointrader.Constants; <ide> import de.dev.eth0.bitcointrader.R; <add>import de.dev.eth0.bitcointrader.service.ExchangeService; <ide> import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity; <ide> import de.dev.eth0.bitcointrader.ui.views.CurrencyAmountView; <ide> import de.schildbach.wallet.ui.HelpDialogFragment; <ide> @Override <ide> public void onAttach(Activity activity) { <ide> super.onAttach(activity); <del> this.activity = (AbstractBitcoinTraderActivity)activity; <del> this.application = (BitcoinTraderApplication)activity.getApplication(); <add> this.activity = (AbstractBitcoinTraderActivity) activity; <add> this.application = (BitcoinTraderApplication) activity.getApplication(); <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public void onViewCreated(View view, Bundle savedInstanceState) { <del> final String currency = getExchangeService().getCurrency(); <ide> <del> percentageTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_percentage_text); <del> priceTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_price_text); <del> updatesTextView = (EditText)view.findViewById(R.id.trailing_stop_dialog_updates_text); <add> percentageTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_percentage_text); <add> priceTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_price_text); <add> updatesTextView = (EditText) view.findViewById(R.id.trailing_stop_dialog_updates_text); <ide> <del> CurrencyAmountView priceView = (CurrencyAmountView)view.findViewById(R.id.trailing_stop_dialog_price); <del> priceView.setCurrencyCode(currency); <del> CurrencyAmountView percentageView = (CurrencyAmountView)view.findViewById(R.id.trailing_stop_dialog_percentage); <add> CurrencyAmountView priceView = (CurrencyAmountView) view.findViewById(R.id.trailing_stop_dialog_price); <add> if (getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { <add> priceView.setCurrencyCode(getExchangeService().getCurrency()); <add> } <add> CurrencyAmountView percentageView = (CurrencyAmountView) view.findViewById(R.id.trailing_stop_dialog_percentage); <ide> percentageView.setCurrencyCode("%"); <del> viewGo = (Button)view.findViewById(R.id.trailing_stop_loss_perform); <add> viewGo = (Button) view.findViewById(R.id.trailing_stop_loss_perform); <ide> viewGo.setOnClickListener(new OnClickListener() { <ide> public void onClick(View v) { <ide> try { <ide> int numberUpdates = 1; <ide> try { <ide> numberUpdates = Integer.parseInt(updates); <del> } <del> catch (NumberFormatException nfe) { <add> } catch (NumberFormatException nfe) { <ide> } <ide> if (!TextUtils.isEmpty(price)) { <add> String currency = "USD"; <add> if(getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { <add> currency = getExchangeService().getCurrency(); <add> } <ide> BigMoney priceCurrency = BigMoney.parse(currency + " 0" + price.toString()); <ide> SharedPreferences.Editor editor = prefs.edit(); <ide> editor.putFloat(Constants.PREFS_TRAILING_STOP_THREASHOLD, threashold); <ide> activity.setResult(Activity.RESULT_OK); <ide> activity.finish(); <ide> } <del> } <del> catch (Exception ex) { <add> } catch (Exception ex) { <ide> Log.w(TAG, ex); <ide> Toast.makeText(getActivity(), R.string.trailing_stop_loss_wrong_input, Toast.LENGTH_LONG).show(); <ide> } <ide> } <ide> }); <ide> <del> viewCancel = (Button)view.findViewById(R.id.trailing_stop_loss_cancel); <add> viewCancel = (Button) view.findViewById(R.id.trailing_stop_loss_cancel); <ide> viewCancel.setOnClickListener(new OnClickListener() { <ide> public void onClick(View v) { <ide> activity.setResult(Activity.RESULT_CANCELED);
Java
bsd-2-clause
841aa7d14c36245744de49d3efae18375793c9de
0
bramp/ffmpeg-cli-wrapper,bramp/ffmpeg-cli-wrapper
package net.bramp.ffmpeg.progress; import com.google.common.base.MoreObjects; import net.bramp.ffmpeg.FFmpegUtils; import org.apache.commons.lang3.math.Fraction; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; /** * TODO Change to be immutable */ public class Progress { public long frame = 0; public Fraction fps = Fraction.ZERO; // TODO stream_0_0_q=0.0 public long bitrate = 0; public long total_size = 0; public long out_time_ms = 0; public long dup_frames = 0; public long drop_frames = 0; public float speed = 0; public String progress = ""; public Progress() { // Nothing } public Progress(long frame, float fps, long bitrate, long total_size, long out_time_ms, long dup_frames, long drop_frames, float speed, String progress) { this.frame = frame; this.fps = Fraction.getFraction(fps); this.bitrate = bitrate; this.total_size = total_size; this.out_time_ms = out_time_ms; this.dup_frames = dup_frames; this.drop_frames = drop_frames; this.speed = speed; this.progress = progress; } /** * Parses values from the line, into this object. * * @param line * @return true if the record is finished */ protected boolean parseLine(String line) { line = checkNotNull(line).trim(); if (line.isEmpty()) { return false; // Skip empty lines } final String[] args = line.split("=", 2); if (args.length != 2) { // invalid argument, so skip return false; } final String key = checkNotNull(args[0]); final String value = checkNotNull(args[1]); switch (key) { case "frame": frame = Long.parseLong(value); return false; case "fps": fps = Fraction.getFraction(value); return false; case "bitrate": // TODO bitrate could be "N/A" bitrate = FFmpegUtils.parseBitrate(value); return false; case "total_size": // TODO could be "N/A" total_size = Long.parseLong(value); return false; case "out_time_ms": out_time_ms = Long.parseLong(value); return false; case "out_time": // There is also out_time_ms, so we ignore out_time. // TODO maybe in the future actually parse out_time, if a out_time_ms wasn't provided. return false; case "dup_frames": dup_frames = Long.parseLong(value); return false; case "drop_frames": drop_frames = Long.parseLong(value); return false; case "speed": // TODO Could be "N/A" speed = Float.parseFloat(value.replace("x", "")); return false; case "progress": // TODO Is only "continue" or "end". Change to enum // TODO After "end" stream is closed progress = value; return true; // The progress field is always last default: // TODO // stream_%d_%d_q= file_index, index, quality // stream_%d_%d_psnr_%c=%2.2f, file_index, index, type{Y, U, V}, quality // Enable with // AV_CODEC_FLAG_PSNR // stream_%d_%d_psnr_all return false; // Ignore for the moment } } public boolean isEnd() { return Objects.equals(progress, "end"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Progress progress1 = (Progress) o; return frame == progress1.frame && bitrate == progress1.bitrate && total_size == progress1.total_size && out_time_ms == progress1.out_time_ms && dup_frames == progress1.dup_frames && drop_frames == progress1.drop_frames && Float.compare(progress1.speed, speed) == 0 && Objects.equals(fps, progress1.fps) && Objects.equals(progress, progress1.progress); } @Override public int hashCode() { return Objects.hash(frame, fps, bitrate, total_size, out_time_ms, dup_frames, drop_frames, speed, progress); } @Override public String toString() { return MoreObjects.toStringHelper(this) // @formatter:off .add("frame", frame) .add("fps", fps) .add("bitrate", bitrate) .add("total_size", total_size) .add("out_time_ms", out_time_ms) .add("dup_frames", dup_frames) .add("drop_frames", drop_frames) .add("speed", speed) .add("progress", progress) // @formatter:on .toString(); } }
src/main/java/net/bramp/ffmpeg/progress/Progress.java
package net.bramp.ffmpeg.progress; import com.google.common.base.MoreObjects; import net.bramp.ffmpeg.FFmpegUtils; import org.apache.commons.lang3.math.Fraction; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; /** * TODO Change to be immutable */ public class Progress { long frame = 0; Fraction fps = Fraction.ZERO; // TODO stream_0_0_q=0.0 long bitrate = 0; long total_size = 0; long out_time_ms = 0; long dup_frames = 0; long drop_frames = 0; float speed = 0; String progress = ""; public Progress() { // Nothing } public Progress(long frame, float fps, long bitrate, long total_size, long out_time_ms, long dup_frames, long drop_frames, float speed, String progress) { this.frame = frame; this.fps = Fraction.getFraction(fps); this.bitrate = bitrate; this.total_size = total_size; this.out_time_ms = out_time_ms; this.dup_frames = dup_frames; this.drop_frames = drop_frames; this.speed = speed; this.progress = progress; } /** * Parses values from the line, into this object. * * @param line * @return true if the record is finished */ protected boolean parseLine(String line) { line = checkNotNull(line).trim(); if (line.isEmpty()) { return false; // Skip empty lines } final String[] args = line.split("=", 2); if (args.length != 2) { // invalid argument, so skip return false; } final String key = checkNotNull(args[0]); final String value = checkNotNull(args[1]); switch (key) { case "frame": frame = Long.parseLong(value); return false; case "fps": fps = Fraction.getFraction(value); return false; case "bitrate": // TODO bitrate could be "N/A" bitrate = FFmpegUtils.parseBitrate(value); return false; case "total_size": // TODO could be "N/A" total_size = Long.parseLong(value); return false; case "out_time_ms": out_time_ms = Long.parseLong(value); return false; case "out_time": // There is also out_time_ms, so we ignore out_time. // TODO maybe in the future actually parse out_time, if a out_time_ms wasn't provided. return false; case "dup_frames": dup_frames = Long.parseLong(value); return false; case "drop_frames": drop_frames = Long.parseLong(value); return false; case "speed": // TODO Could be "N/A" speed = Float.parseFloat(value.replace("x", "")); return false; case "progress": // TODO Is only "continue" or "end". Change to enum // TODO After "end" stream is closed progress = value; return true; // The progress field is always last default: // TODO // stream_%d_%d_q= file_index, index, quality // stream_%d_%d_psnr_%c=%2.2f, file_index, index, type{Y, U, V}, quality // Enable with // AV_CODEC_FLAG_PSNR // stream_%d_%d_psnr_all return false; // Ignore for the moment } } public boolean isEnd() { return Objects.equals(progress, "end"); } @Override public String toString() { return MoreObjects.toStringHelper(this) // @formatter:off .add("frame", frame) .add("fps", fps) .add("bitrate", bitrate) .add("total_size", total_size) .add("out_time_ms", out_time_ms) .add("dup_frames", dup_frames) .add("drop_frames", drop_frames) .add("speed", speed) .add("progress", progress) // @formatter:on .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Progress progress1 = (Progress) o; return frame == progress1.frame && bitrate == progress1.bitrate && total_size == progress1.total_size && out_time_ms == progress1.out_time_ms && dup_frames == progress1.dup_frames && drop_frames == progress1.drop_frames && Float.compare(progress1.speed, speed) == 0 && Objects.equals(fps, progress1.fps) && Objects.equals(progress, progress1.progress); } @Override public int hashCode() { return Objects.hash(frame, fps, bitrate, total_size, out_time_ms, dup_frames, drop_frames, speed, progress); @Override public String toString() { return MoreObjects.toStringHelper(this) // @formatter:off .add("frame", frame) .add("fps", fps) .add("bitrate", bitrate) .add("total_size", total_size) .add("out_time_ms", out_time_ms) .add("dup_frames", dup_frames) .add("drop_frames", drop_frames) .add("speed", speed) .add("progress", progress) // @formatter:on .toString(); } }
Made the various Progress members public, and fixed a build error (due to a bad merge).
src/main/java/net/bramp/ffmpeg/progress/Progress.java
Made the various Progress members public, and fixed a build error (due to a bad merge).
<ide><path>rc/main/java/net/bramp/ffmpeg/progress/Progress.java <ide> * TODO Change to be immutable <ide> */ <ide> public class Progress { <del> long frame = 0; <del> Fraction fps = Fraction.ZERO; <add> public long frame = 0; <add> public Fraction fps = Fraction.ZERO; <ide> <ide> // TODO stream_0_0_q=0.0 <ide> <del> long bitrate = 0; <del> long total_size = 0; <del> long out_time_ms = 0; <add> public long bitrate = 0; <add> public long total_size = 0; <add> public long out_time_ms = 0; <ide> <del> long dup_frames = 0; <del> long drop_frames = 0; <del> float speed = 0; <del> String progress = ""; <add> public long dup_frames = 0; <add> public long drop_frames = 0; <add> public float speed = 0; <add> public String progress = ""; <ide> <ide> public Progress() { <ide> // Nothing <ide> } <ide> <ide> @Override <del> public String toString() { <del> return MoreObjects.toStringHelper(this) <del> // @formatter:off <del> .add("frame", frame) <del> .add("fps", fps) <del> .add("bitrate", bitrate) <del> .add("total_size", total_size) <del> .add("out_time_ms", out_time_ms) <del> .add("dup_frames", dup_frames) <del> .add("drop_frames", drop_frames) <del> .add("speed", speed) <del> .add("progress", progress) <del> // @formatter:on <del> .toString(); <del> } <del> <del> @Override <ide> public boolean equals(Object o) { <ide> if (this == o) <ide> return true; <ide> public int hashCode() { <ide> return Objects.hash(frame, fps, bitrate, total_size, out_time_ms, dup_frames, drop_frames, <ide> speed, progress); <add> } <ide> <ide> @Override <ide> public String toString() {
Java
lgpl-2.1
24b4b2bd2582cbe3e44db44fd1d6b930e207b984
0
gallardo/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,MenZil/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,victos/opencms-core,victos/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,victos/opencms-core,victos/opencms-core,ggiudetti/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db.generic; import org.opencms.db.CmsCompositeQueryFragment; import org.opencms.db.CmsDbUtil; import org.opencms.db.CmsPagingQuery; import org.opencms.db.CmsSelectQuery; import org.opencms.db.CmsSelectQuery.TableAlias; import org.opencms.db.CmsSimpleQueryFragment; import org.opencms.db.CmsSqlBooleanClause; import org.opencms.db.CmsStatementBuilder; import org.opencms.db.I_CmsQueryFragment; import org.opencms.file.CmsGroup; import org.opencms.file.CmsUserSearchParameters; import org.opencms.file.CmsUserSearchParameters.SearchKey; import org.opencms.file.CmsUserSearchParameters.SortKey; import org.opencms.i18n.CmsEncoder; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsPair; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.util.Collection; import java.util.List; import com.google.common.base.Joiner; /** * Default implementation of the user query builder.<p> * * @since 8.0.0 */ public class CmsUserQueryBuilder { /** * Creates a query for searching users.<p> * * @param searchParams the user search criteria * @param countOnly if true, the query will only count the total number of results instead of returning them * * @return a pair consisting of the query string and its parameters */ public CmsPair<String, List<Object>> createUserQuery(CmsUserSearchParameters searchParams, boolean countOnly) { CmsSelectQuery select = new CmsSelectQuery(); TableAlias users = select.addTable(tabUsers(), "usr"); if (countOnly) { select.addColumn("COUNT(" + users.column(colId()) + ")"); } else { String[] columns = new String[] { colId(), colName(), colPassword(), colFirstName(), colLastName(), colEmail(), colLastLogin(), colFlags(), colOu(), colDateCreated()}; for (String columnName : columns) { select.addColumn(users.column(columnName)); } } CmsOrganizationalUnit orgUnit = searchParams.getOrganizationalUnit(); boolean recursive = searchParams.recursiveOrgUnits(); if (orgUnit != null) { addOrgUnitCondition(select, users, orgUnit, recursive); } if (searchParams.isFilterCore()) { select.addCondition(createCoreCondition(users)); } addAllowedOuCondition(select, users, searchParams.getAllowedOus()); addFlagCondition(select, users, searchParams.getFlags(), searchParams.keepCoreUsers()); if (orgUnit != null) { addWebuserCondition(select, orgUnit, users); } addSearchFilterCondition(select, users, searchParams); addGroupCondition(select, users, searchParams); if (countOnly) { CmsStatementBuilder builder = new CmsStatementBuilder(); select.visit(builder); return CmsPair.create(builder.getQuery(), builder.getParameters()); } else { addSorting(select, users, searchParams); return makePaged(select, searchParams); } } /** * Adds OU conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param allowedOus the allowed ous */ protected void addAllowedOuCondition(CmsSelectQuery select, TableAlias users, List<CmsOrganizationalUnit> allowedOus) { if ((allowedOus != null) && !allowedOus.isEmpty()) { CmsCompositeQueryFragment ouCondition = new CmsCompositeQueryFragment(); ouCondition.setPrefix("("); ouCondition.setSuffix(")"); ouCondition.setSeparator(" OR "); for (CmsOrganizationalUnit ou : allowedOus) { String ouName = CmsStringUtil.joinPaths("/", ou.getName()); ouCondition.add(new CmsSimpleQueryFragment(users.column(colOu()) + " = ? ", ouName)); } select.addCondition(ouCondition); } } /** * Adds flag checking conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param flags the flags * @param allowCore set to true if core users should not be filtered out */ protected void addFlagCondition(CmsSelectQuery select, TableAlias users, int flags, boolean allowCore) { if (flags != 0) { I_CmsQueryFragment condition = createFlagCondition(users, flags); if (allowCore) { I_CmsQueryFragment coreCondition = createCoreCondition(users); select.addCondition(CmsSqlBooleanClause.makeOr(condition, coreCondition)); } else { select.addCondition(condition); } } } /** * Adds group conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param searchParams the search parameters */ protected void addGroupCondition(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { CmsGroup group = searchParams.getGroup(); if (group != null) { CmsUUID groupId = group.getId(); TableAlias groupUsers = select.addTable(tabGroupUsers(), "groupusrs"); select.addCondition(new CmsSimpleQueryFragment( groupUsers.column(colGroupUserGroupId()) + " = ? ", groupId.toString())); select.addCondition(new CmsSimpleQueryFragment(groupUsers.column(colGroupUserUserId()) + " = " + users.column(colId()))); if (searchParams.isFilterByGroupOu()) { select.addCondition(new CmsSimpleQueryFragment(users.column(colOu()) + " = ? ", group.getOuFqn())); } } CmsGroup notGroup = searchParams.getNotGroup(); if (notGroup != null) { CmsSimpleQueryFragment notGroupCondition = new CmsSimpleQueryFragment("NOT EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND GU." + colGroupUserGroupId() + " = ?)", notGroup.getId().toString()); select.addCondition(notGroupCondition); } Collection<CmsGroup> anyGroups = searchParams.getAnyGroups(); if ((anyGroups != null) && !anyGroups.isEmpty()) { CmsCompositeQueryFragment groupClause = new CmsCompositeQueryFragment(); groupClause.setSeparator(" OR "); for (CmsGroup grp : anyGroups) { groupClause.add(new CmsSimpleQueryFragment( "GU." + colGroupUserGroupId() + " = ?", grp.getId().toString())); } CmsCompositeQueryFragment existsClause = new CmsCompositeQueryFragment(); existsClause.add(new CmsSimpleQueryFragment("EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND ")); existsClause.add(groupClause); existsClause.add(new CmsSimpleQueryFragment(" ) ")); select.addCondition(existsClause); } Collection<CmsGroup> notAnyGroups = searchParams.getNotAnyGroups(); if ((notAnyGroups != null) && (!notAnyGroups.isEmpty())) { CmsCompositeQueryFragment groupClause = new CmsCompositeQueryFragment(); groupClause.setPrefix("("); groupClause.setSuffix(")"); groupClause.setSeparator(" OR "); for (CmsGroup grp : notAnyGroups) { groupClause.add(new CmsSimpleQueryFragment( "GU." + colGroupUserGroupId() + " = ?", grp.getId().toString())); } CmsCompositeQueryFragment notExistsClause = new CmsCompositeQueryFragment(); notExistsClause.add(new CmsSimpleQueryFragment("NOT EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND ")); notExistsClause.add(groupClause); notExistsClause.add(new CmsSimpleQueryFragment(" ) ")); select.addCondition(notExistsClause); } } /** * Adds a check for an OU to an SQL query.<p> * * @param select the query * @param users the user table alias * @param orgUnit the organizational unit * @param recursive if true, checks for sub-OUs too */ protected void addOrgUnitCondition( CmsSelectQuery select, TableAlias users, CmsOrganizationalUnit orgUnit, boolean recursive) { String ouName = orgUnit.getName(); String pattern = CmsOrganizationalUnit.SEPARATOR + ouName; if (recursive) { pattern += "%"; } select.addCondition(CmsDbUtil.columnLike(users.column(colOu()), pattern)); } /** * Adds a search condition to a query.<p> * * @param select the query * @param users the user table alias * @param searchParams the search criteria */ protected void addSearchFilterCondition( CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { String searchFilter = searchParams.getSearchFilter(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchFilter)) { boolean caseInsensitive = !searchParams.isCaseSensitive(); if (caseInsensitive) { searchFilter = searchFilter.toLowerCase(); } CmsCompositeQueryFragment searchCondition = new CmsCompositeQueryFragment(); searchCondition.setSeparator(" OR "); searchCondition.setPrefix("("); searchCondition.setSuffix(")"); //use coalesce in case any of the name columns are null String patternExprTemplate = generateConcat( "COALESCE(%1$s, '')", "' '", "COALESCE(%2$s, '')", "' '", "COALESCE(%3$s, '')"); patternExprTemplate = wrapLower(patternExprTemplate, caseInsensitive); String patternExpr = String.format( patternExprTemplate, users.column(colName()), users.column(colFirstName()), users.column(colLastName())); String like = " LIKE ? ESCAPE '!' "; String matchExpr = patternExpr + like; searchFilter = "%" + CmsEncoder.escapeSqlLikePattern(searchFilter, '!') + '%'; searchCondition.add(new CmsSimpleQueryFragment(matchExpr, searchFilter)); for (SearchKey key : searchParams.getSearchKeys()) { switch (key) { case email: searchCondition.add(new CmsSimpleQueryFragment(wrapLower( users.column(colEmail()), caseInsensitive) + like, searchFilter)); break; case orgUnit: searchCondition.add(new CmsSimpleQueryFragment( wrapLower(users.column(colOu()), caseInsensitive) + like, searchFilter)); break; default: break; } } select.addCondition(searchCondition); } } /** * Adds a sort order to an SQL query.<p> * * @param select the query * @param users the user table alias * @param searchParams the user search criteria */ protected void addSorting(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { boolean ascending = searchParams.isAscending(); String ordering = getSortExpression(users, searchParams); if (ascending) { ordering += " ASC"; } else { ordering += " DESC"; } select.setOrdering(ordering); } /** * Adds a check for the web user condition to an SQL query.<p> * * @param select the query * @param orgUnit the organizational unit * @param users the user table alias */ protected void addWebuserCondition(CmsSelectQuery select, CmsOrganizationalUnit orgUnit, TableAlias users) { String webuserConditionTemplate; if (orgUnit.hasFlagWebuser()) { webuserConditionTemplate = "( %1$s >= 32768 AND %1$s < 65536 )"; } else { webuserConditionTemplate = "( %1$s < 32768 OR %1$s >= 65536 )"; } String webuserCondition = String.format(webuserConditionTemplate, users.column(colFlags())); select.addCondition(webuserCondition); } /** * Column name accessor.<p> * * @return the name of the column */ protected String colDateCreated() { return "USER_DATECREATED"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colEmail() { return "USER_EMAIL"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colFirstName() { return "USER_FIRSTNAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colFlags() { return "USER_FLAGS"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colGroupUserGroupId() { return "GROUP_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colGroupUserUserId() { return "USER_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colId() { return "USER_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colLastLogin() { return "USER_LASTLOGIN"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colLastName() { return "USER_LASTNAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colName() { return "USER_NAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colOu() { return "USER_OU"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colPassword() { return "USER_PASSWORD"; } /** * Creates a core user check condition.<p> * * @param users the user table alias * * @return the resulting SQL expression */ protected I_CmsQueryFragment createCoreCondition(TableAlias users) { return new CmsSimpleQueryFragment(users.column(colFlags()) + " <= " + I_CmsPrincipal.FLAG_CORE_LIMIT); } /** * Creates an SQL flag check condition.<p> * * @param users the user table alias * @param flags the flags to check * * @return the resulting SQL expression */ protected I_CmsQueryFragment createFlagCondition(TableAlias users, int flags) { return new CmsSimpleQueryFragment( users.column(colFlags()) + " & ? = ? ", new Integer(flags), new Integer(flags)); } /** * Generates an SQL expression for concatenating several other SQL expressions.<p> * * @param expressions the expressions to concatenate * * @return the concat expression */ protected String generateConcat(String... expressions) { return "CONCAT(" + Joiner.on(", ").join(expressions) + ")"; } /** * Generates an SQL expression for trimming whitespace from the beginning and end of a string.<p> * * @param expression the expression to wrap * * @return the expression for trimming the given expression */ protected String generateTrim(String expression) { return "TRIM(" + expression + ")"; } /** * Returns the columns that should be returned by user subqueries.<p> * * @return the columns that should be returned by user subqueries */ protected String getGroupUserSubqueryColumns() { return "*"; } /** * Returns the expression used for sorting the results.<p> * * @param users the user table alias * @param searchParams the search parameters * * @return the sorting expressiong */ protected String getSortExpression(TableAlias users, CmsUserSearchParameters searchParams) { SortKey sortKey = searchParams.getSortKey(); String ordering = users.column(colId()); if (sortKey != null) { switch (sortKey) { case email: ordering = users.column(colEmail()); break; case loginName: ordering = users.column(colName()); break; case fullName: ordering = getUserFullNameExpression(users); break; case lastLogin: ordering = users.column(colLastLogin()); break; case orgUnit: ordering = users.column(colOu()); break; case activated: ordering = getUserActivatedExpression(users); break; case flagStatus: ordering = getUserFlagExpression(users, searchParams.getSortFlags()); break; default: break; } } return ordering; } /** * Returns an expression for checking whether a user is activated.<p> * * @param users the user table alias * * @return the expression for checking whether the user is activated */ protected String getUserActivatedExpression(TableAlias users) { return "MOD(" + users.column(colFlags()) + ", 2)"; } /** * Returns a bitwise AND expression with a fixed second operand.<p> * * @param users the user table alias * @param flags the user flags * @return the resulting SQL expression */ protected String getUserFlagExpression(TableAlias users, int flags) { return users.column(colFlags()) + " & " + flags; } /** * Returns the SQL expression for generating the user's full name in the format * 'firstname lastname (loginname)'.<p> * * @param users the user table alias * * @return the expression for generating the user's full name */ protected String getUserFullNameExpression(TableAlias users) { //use coalesce in case any of the name columns are null String template = generateTrim(generateConcat( "COALESCE(%1$s, '')", "' '", "COALESCE(%2$s, '')", "' ('", "%3$s", "')'")); return String.format( template, users.column(colFirstName()), users.column(colLastName()), users.column(colName())); } /** * Creates a query which uses paging from another query.<p> * * @param select the base query * @param params the query parameters * * @return the paged version of the query */ protected CmsPair<String, List<Object>> makePaged(CmsSelectQuery select, CmsUserSearchParameters params) { CmsPagingQuery paging = new CmsPagingQuery(select); paging.setUseWindowFunctions(useWindowFunctionsForPaging()); int page = params.getPage(); int pageSize = params.getPageSize(); paging.setNameSubquery(shouldNameSubqueries()); paging.setPaging(pageSize, page); CmsStatementBuilder builder = new CmsStatementBuilder(); paging.visit(builder); return CmsPair.create(builder.getQuery(), builder.getParameters()); } /** * Should return true if subqueries in a FROM clause should be named.<p> * * @return true if subqueries in a FROM clause should be named */ protected boolean shouldNameSubqueries() { return false; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabGroups() { return "CMS_GROUPS"; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabGroupUsers() { return "CMS_GROUPUSERS"; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabUsers() { return "CMS_USERS"; } /** * Returns true if window functions should be used for paging.<p> * * @return true if window functions should be used for paging */ protected boolean useWindowFunctionsForPaging() { return false; } /** * Wraps an SQL expression in a "LOWER" call conditionally.<p> * * @param expr the expression to wrap * @param caseInsensitive if false, no wrapping should occur * * @return the resulting expression */ protected String wrapLower(String expr, boolean caseInsensitive) { return caseInsensitive ? "LOWER(" + expr + ")" : expr; } }
src/org/opencms/db/generic/CmsUserQueryBuilder.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db.generic; import org.opencms.db.CmsCompositeQueryFragment; import org.opencms.db.CmsDbUtil; import org.opencms.db.CmsPagingQuery; import org.opencms.db.CmsSelectQuery; import org.opencms.db.CmsSimpleQueryFragment; import org.opencms.db.CmsSqlBooleanClause; import org.opencms.db.CmsStatementBuilder; import org.opencms.db.I_CmsQueryFragment; import org.opencms.db.CmsSelectQuery.TableAlias; import org.opencms.file.CmsGroup; import org.opencms.file.CmsUserSearchParameters; import org.opencms.file.CmsUserSearchParameters.SearchKey; import org.opencms.file.CmsUserSearchParameters.SortKey; import org.opencms.i18n.CmsEncoder; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsPair; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.util.Collection; import java.util.List; import com.google.common.base.Joiner; /** * Default implementation of the user query builder.<p> * * @since 8.0.0 */ public class CmsUserQueryBuilder { /** * Creates a query for searching users.<p> * * @param searchParams the user search criteria * @param countOnly if true, the query will only count the total number of results instead of returning them * * @return a pair consisting of the query string and its parameters */ public CmsPair<String, List<Object>> createUserQuery(CmsUserSearchParameters searchParams, boolean countOnly) { CmsSelectQuery select = new CmsSelectQuery(); TableAlias users = select.addTable(tabUsers(), "usr"); if (countOnly) { select.addColumn("COUNT(" + users.column(colId()) + ")"); } else { String[] columns = new String[] { colId(), colName(), colPassword(), colFirstName(), colLastName(), colEmail(), colLastLogin(), colFlags(), colOu(), colDateCreated()}; for (String columnName : columns) { select.addColumn(users.column(columnName)); } } CmsOrganizationalUnit orgUnit = searchParams.getOrganizationalUnit(); boolean recursive = searchParams.recursiveOrgUnits(); if (orgUnit != null) { addOrgUnitCondition(select, users, orgUnit, recursive); } if (searchParams.isFilterCore()) { select.addCondition(createCoreCondition(users)); } addAllowedOuCondition(select, users, searchParams.getAllowedOus()); addFlagCondition(select, users, searchParams.getFlags(), searchParams.keepCoreUsers()); if (orgUnit != null) { addWebuserCondition(select, orgUnit, users); } addSearchFilterCondition(select, users, searchParams); addGroupCondition(select, users, searchParams); if (countOnly) { CmsStatementBuilder builder = new CmsStatementBuilder(); select.visit(builder); return CmsPair.create(builder.getQuery(), builder.getParameters()); } else { addSorting(select, users, searchParams); return makePaged(select, searchParams); } } /** * Adds OU conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param allowedOus the allowed ous */ protected void addAllowedOuCondition(CmsSelectQuery select, TableAlias users, List<CmsOrganizationalUnit> allowedOus) { if ((allowedOus != null) && !allowedOus.isEmpty()) { CmsCompositeQueryFragment ouCondition = new CmsCompositeQueryFragment(); ouCondition.setPrefix("("); ouCondition.setSuffix(")"); ouCondition.setSeparator(" OR "); for (CmsOrganizationalUnit ou : allowedOus) { String ouName = CmsStringUtil.joinPaths("/", ou.getName()); ouCondition.add(new CmsSimpleQueryFragment(users.column(colOu()) + " = ? ", ouName)); } select.addCondition(ouCondition); } } /** * Adds flag checking conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param flags the flags * @param allowCore set to true if core users should not be filtered out */ protected void addFlagCondition(CmsSelectQuery select, TableAlias users, int flags, boolean allowCore) { if (flags != 0) { I_CmsQueryFragment condition = createFlagCondition(users, flags); if (allowCore) { I_CmsQueryFragment coreCondition = createCoreCondition(users); select.addCondition(CmsSqlBooleanClause.makeOr(condition, coreCondition)); } else { select.addCondition(condition); } } } /** * Adds group conditions to an SQL query.<p> * * @param select the query * @param users the user table alias * @param searchParams the search parameters */ protected void addGroupCondition(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { CmsGroup group = searchParams.getGroup(); if (group != null) { CmsUUID groupId = group.getId(); TableAlias groupUsers = select.addTable(tabGroupUsers(), "groupusrs"); select.addCondition(new CmsSimpleQueryFragment( groupUsers.column(colGroupUserGroupId()) + " = ? ", groupId.toString())); select.addCondition(new CmsSimpleQueryFragment(groupUsers.column(colGroupUserUserId()) + " = " + users.column(colId()))); if (searchParams.isFilterByGroupOu()) { select.addCondition(new CmsSimpleQueryFragment(users.column(colOu()) + " = ? ", group.getOuFqn())); } } CmsGroup notGroup = searchParams.getNotGroup(); if (notGroup != null) { CmsSimpleQueryFragment notGroupCondition = new CmsSimpleQueryFragment("NOT EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND GU." + colGroupUserGroupId() + " = ?)", notGroup.getId().toString()); select.addCondition(notGroupCondition); } Collection<CmsGroup> anyGroups = searchParams.getAnyGroups(); if ((anyGroups != null) && !anyGroups.isEmpty()) { CmsCompositeQueryFragment groupClause = new CmsCompositeQueryFragment(); groupClause.setSeparator(" OR "); for (CmsGroup grp : anyGroups) { groupClause.add(new CmsSimpleQueryFragment( "GU." + colGroupUserGroupId() + " = ?", grp.getId().toString())); } CmsCompositeQueryFragment existsClause = new CmsCompositeQueryFragment(); existsClause.add(new CmsSimpleQueryFragment("EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND ")); existsClause.add(groupClause); existsClause.add(new CmsSimpleQueryFragment(" ) ")); select.addCondition(existsClause); } Collection<CmsGroup> notAnyGroups = searchParams.getNotAnyGroups(); if ((notAnyGroups != null) && (!notAnyGroups.isEmpty())) { CmsCompositeQueryFragment groupClause = new CmsCompositeQueryFragment(); groupClause.setPrefix("("); groupClause.setSuffix(")"); groupClause.setSeparator(" OR "); for (CmsGroup grp : notAnyGroups) { groupClause.add(new CmsSimpleQueryFragment( "GU." + colGroupUserGroupId() + " = ?", grp.getId().toString())); } CmsCompositeQueryFragment notExistsClause = new CmsCompositeQueryFragment(); notExistsClause.add(new CmsSimpleQueryFragment("NOT EXISTS (SELECT " + getGroupUserSubqueryColumns() + " FROM " + tabGroupUsers() + " GU WHERE GU." + colGroupUserUserId() + " = " + users.column(colId()) + " AND ")); notExistsClause.add(groupClause); notExistsClause.add(new CmsSimpleQueryFragment(" ) ")); select.addCondition(notExistsClause); } } /** * Adds a check for an OU to an SQL query.<p> * * @param select the query * @param users the user table alias * @param orgUnit the organizational unit * @param recursive if true, checks for sub-OUs too */ protected void addOrgUnitCondition( CmsSelectQuery select, TableAlias users, CmsOrganizationalUnit orgUnit, boolean recursive) { String ouName = orgUnit.getName(); String pattern = CmsOrganizationalUnit.SEPARATOR + ouName; if (recursive) { pattern += "%"; } select.addCondition(CmsDbUtil.columnLike(users.column(colOu()), pattern)); } /** * Adds a search condition to a query.<p> * * @param select the query * @param users the user table alias * @param searchParams the search criteria */ protected void addSearchFilterCondition( CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { String searchFilter = searchParams.getSearchFilter(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchFilter)) { boolean caseInsensitive = !searchParams.isCaseSensitive(); if (caseInsensitive) { searchFilter = searchFilter.toLowerCase(); } CmsCompositeQueryFragment searchCondition = new CmsCompositeQueryFragment(); searchCondition.setSeparator(" OR "); searchCondition.setPrefix("("); searchCondition.setSuffix(")"); //use coalesce in case any of the name columns are null String patternExprTemplate = generateConcat( "COALESCE(%1$s, '')", "' '", "COALESCE(%2$s, '')", "' '", "COALESCE(%3$s, '')"); patternExprTemplate = wrapLower(patternExprTemplate, caseInsensitive); String patternExpr = String.format( patternExprTemplate, users.column(colName()), users.column(colFirstName()), users.column(colLastName())); String like = " LIKE ? ESCAPE '!' "; String matchExpr = patternExpr + like; searchFilter = "%" + CmsEncoder.escapeSqlLikePattern(searchFilter, '!') + '%'; searchCondition.add(new CmsSimpleQueryFragment(matchExpr, searchFilter)); for (SearchKey key : searchParams.getSearchKeys()) { switch (key) { case email: searchCondition.add(new CmsSimpleQueryFragment(wrapLower( users.column(colEmail()), caseInsensitive) + like, searchFilter)); break; case orgUnit: searchCondition.add(new CmsSimpleQueryFragment( wrapLower(users.column(colOu()), caseInsensitive) + like, searchFilter)); break; default: break; } } select.addCondition(searchCondition); } } /** * Adds a sort order to an SQL query.<p> * * @param select the query * @param users the user table alias * @param searchParams the user search criteria */ protected void addSorting(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { boolean ascending = searchParams.isAscending(); String ordering = getSortExpression(users, searchParams); if (ascending) { ordering += " ASC"; } else { ordering += " DESC"; } select.setOrdering(ordering); } /** * Adds a check for the web user condition to an SQL query.<p> * * @param select the query * @param orgUnit the organizational unit * @param users the user table alias */ protected void addWebuserCondition(CmsSelectQuery select, CmsOrganizationalUnit orgUnit, TableAlias users) { String webuserConditionTemplate; if (orgUnit.hasFlagWebuser()) { webuserConditionTemplate = "( %1$ >= 32768 AND %1$s < 65536 )"; } else { webuserConditionTemplate = "( %1$s < 32768 OR %1$s >= 65536 )"; } String webuserCondition = String.format(webuserConditionTemplate, users.column(colFlags())); select.addCondition(webuserCondition); } /** * Column name accessor.<p> * * @return the name of the column */ protected String colDateCreated() { return "USER_DATECREATED"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colEmail() { return "USER_EMAIL"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colFirstName() { return "USER_FIRSTNAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colFlags() { return "USER_FLAGS"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colGroupUserGroupId() { return "GROUP_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colGroupUserUserId() { return "USER_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colId() { return "USER_ID"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colLastLogin() { return "USER_LASTLOGIN"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colLastName() { return "USER_LASTNAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colName() { return "USER_NAME"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colOu() { return "USER_OU"; } /** * Column name accessor.<p> * * @return the name of the column */ protected String colPassword() { return "USER_PASSWORD"; } /** * Creates a core user check condition.<p> * * @param users the user table alias * * @return the resulting SQL expression */ protected I_CmsQueryFragment createCoreCondition(TableAlias users) { return new CmsSimpleQueryFragment(users.column(colFlags()) + " <= " + I_CmsPrincipal.FLAG_CORE_LIMIT); } /** * Creates an SQL flag check condition.<p> * * @param users the user table alias * @param flags the flags to check * * @return the resulting SQL expression */ protected I_CmsQueryFragment createFlagCondition(TableAlias users, int flags) { return new CmsSimpleQueryFragment( users.column(colFlags()) + " & ? = ? ", new Integer(flags), new Integer(flags)); } /** * Generates an SQL expression for concatenating several other SQL expressions.<p> * * @param expressions the expressions to concatenate * * @return the concat expression */ protected String generateConcat(String... expressions) { return "CONCAT(" + Joiner.on(", ").join(expressions) + ")"; } /** * Generates an SQL expression for trimming whitespace from the beginning and end of a string.<p> * * @param expression the expression to wrap * * @return the expression for trimming the given expression */ protected String generateTrim(String expression) { return "TRIM(" + expression + ")"; } /** * Returns the columns that should be returned by user subqueries.<p> * * @return the columns that should be returned by user subqueries */ protected String getGroupUserSubqueryColumns() { return "*"; } /** * Returns the expression used for sorting the results.<p> * * @param users the user table alias * @param searchParams the search parameters * * @return the sorting expressiong */ protected String getSortExpression(TableAlias users, CmsUserSearchParameters searchParams) { SortKey sortKey = searchParams.getSortKey(); String ordering = users.column(colId()); if (sortKey != null) { switch (sortKey) { case email: ordering = users.column(colEmail()); break; case loginName: ordering = users.column(colName()); break; case fullName: ordering = getUserFullNameExpression(users); break; case lastLogin: ordering = users.column(colLastLogin()); break; case orgUnit: ordering = users.column(colOu()); break; case activated: ordering = getUserActivatedExpression(users); break; case flagStatus: ordering = getUserFlagExpression(users, searchParams.getSortFlags()); break; default: break; } } return ordering; } /** * Returns an expression for checking whether a user is activated.<p> * * @param users the user table alias * * @return the expression for checking whether the user is activated */ protected String getUserActivatedExpression(TableAlias users) { return "MOD(" + users.column(colFlags()) + ", 2)"; } /** * Returns a bitwise AND expression with a fixed second operand.<p> * * @param users the user table alias * @param flags the user flags * @return the resulting SQL expression */ protected String getUserFlagExpression(TableAlias users, int flags) { return users.column(colFlags()) + " & " + flags; } /** * Returns the SQL expression for generating the user's full name in the format * 'firstname lastname (loginname)'.<p> * * @param users the user table alias * * @return the expression for generating the user's full name */ protected String getUserFullNameExpression(TableAlias users) { //use coalesce in case any of the name columns are null String template = generateTrim(generateConcat( "COALESCE(%1$s, '')", "' '", "COALESCE(%2$s, '')", "' ('", "%3$s", "')'")); return String.format( template, users.column(colFirstName()), users.column(colLastName()), users.column(colName())); } /** * Creates a query which uses paging from another query.<p> * * @param select the base query * @param params the query parameters * * @return the paged version of the query */ protected CmsPair<String, List<Object>> makePaged(CmsSelectQuery select, CmsUserSearchParameters params) { CmsPagingQuery paging = new CmsPagingQuery(select); paging.setUseWindowFunctions(useWindowFunctionsForPaging()); int page = params.getPage(); int pageSize = params.getPageSize(); paging.setNameSubquery(shouldNameSubqueries()); paging.setPaging(pageSize, page); CmsStatementBuilder builder = new CmsStatementBuilder(); paging.visit(builder); return CmsPair.create(builder.getQuery(), builder.getParameters()); } /** * Should return true if subqueries in a FROM clause should be named.<p> * * @return true if subqueries in a FROM clause should be named */ protected boolean shouldNameSubqueries() { return false; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabGroups() { return "CMS_GROUPS"; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabGroupUsers() { return "CMS_GROUPUSERS"; } /** * Table name accessor.<p> * * @return the name of a table */ protected String tabUsers() { return "CMS_USERS"; } /** * Returns true if window functions should be used for paging.<p> * * @return true if window functions should be used for paging */ protected boolean useWindowFunctionsForPaging() { return false; } /** * Wraps an SQL expression in a "LOWER" call conditionally.<p> * * @param expr the expression to wrap * @param caseInsensitive if false, no wrapping should occur * * @return the resulting expression */ protected String wrapLower(String expr, boolean caseInsensitive) { return caseInsensitive ? "LOWER(" + expr + ")" : expr; } }
Fixing issue with the web user query template.
src/org/opencms/db/generic/CmsUserQueryBuilder.java
Fixing issue with the web user query template.
<ide><path>rc/org/opencms/db/generic/CmsUserQueryBuilder.java <ide> import org.opencms.db.CmsDbUtil; <ide> import org.opencms.db.CmsPagingQuery; <ide> import org.opencms.db.CmsSelectQuery; <add>import org.opencms.db.CmsSelectQuery.TableAlias; <ide> import org.opencms.db.CmsSimpleQueryFragment; <ide> import org.opencms.db.CmsSqlBooleanClause; <ide> import org.opencms.db.CmsStatementBuilder; <ide> import org.opencms.db.I_CmsQueryFragment; <del>import org.opencms.db.CmsSelectQuery.TableAlias; <ide> import org.opencms.file.CmsGroup; <ide> import org.opencms.file.CmsUserSearchParameters; <ide> import org.opencms.file.CmsUserSearchParameters.SearchKey; <ide> case email: <ide> searchCondition.add(new CmsSimpleQueryFragment(wrapLower( <ide> users.column(colEmail()), <del> caseInsensitive) <del> + like, searchFilter)); <add> caseInsensitive) + like, searchFilter)); <ide> break; <ide> case orgUnit: <ide> searchCondition.add(new CmsSimpleQueryFragment( <ide> <ide> String webuserConditionTemplate; <ide> if (orgUnit.hasFlagWebuser()) { <del> webuserConditionTemplate = "( %1$ >= 32768 AND %1$s < 65536 )"; <add> webuserConditionTemplate = "( %1$s >= 32768 AND %1$s < 65536 )"; <ide> } else { <ide> webuserConditionTemplate = "( %1$s < 32768 OR %1$s >= 65536 )"; <ide> }
Java
lgpl-2.1
082b130f7811af306653d4a76721b549a733441c
0
JiriOndrusek/wildfly-core,JiriOndrusek/wildfly-core,jfdenise/wildfly-core,soul2zimate/wildfly-core,luck3y/wildfly-core,jfdenise/wildfly-core,bstansberry/wildfly-core,jamezp/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,darranl/wildfly-core,jamezp/wildfly-core,aloubyansky/wildfly-core,jfdenise/wildfly-core,yersan/wildfly-core,bstansberry/wildfly-core,soul2zimate/wildfly-core,ivassile/wildfly-core,aloubyansky/wildfly-core,luck3y/wildfly-core,darranl/wildfly-core,luck3y/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core,ivassile/wildfly-core,aloubyansky/wildfly-core,yersan/wildfly-core,darranl/wildfly-core,JiriOndrusek/wildfly-core,soul2zimate/wildfly-core
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.domain.management.access; import java.util.Collections; import java.util.Set; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReadResourceNameOperationStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleListAttributeDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.access.management.AccessConstraintUtilization; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.Resource; import org.jboss.as.domain.management._private.DomainManagementResolver; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * {@code ResourceDefinition} for the resources that expose what resources an * {@link org.jboss.as.controller.access.management.AccessConstraintDefinition} applies to. * * @author Brian Stansberry (c) 2013 Red Hat Inc. */ public class AccessConstraintAppliesToResourceDefinition extends SimpleResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(ModelDescriptionConstants.APPLIES_TO); public static final AttributeDefinition ADDRESS = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ADDRESS, ModelType.STRING).build(); public static final AttributeDefinition ENTIRE_RESOURCE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ENTIRE_RESOURCE, ModelType.BOOLEAN) .build(); public static final AttributeDefinition ATTRIBUTES = new SimpleListAttributeDefinition.Builder(ModelDescriptionConstants.ATTRIBUTES, new SimpleAttributeDefinitionBuilder("attribute", ModelType.STRING).build()) .build(); public static final AttributeDefinition OPERATIONS = new SimpleListAttributeDefinition.Builder(ModelDescriptionConstants.OPERATIONS, new SimpleAttributeDefinitionBuilder("operation", ModelType.STRING).build()) .build(); public AccessConstraintAppliesToResourceDefinition() { super(PATH_ELEMENT, DomainManagementResolver.getResolver("core.access-control.constraint.applies-to")); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(ADDRESS, ReadResourceNameOperationStepHandler.INSTANCE); resourceRegistration.registerReadOnlyAttribute(ENTIRE_RESOURCE, new EntireResourceHandler()); resourceRegistration.registerReadOnlyAttribute(ATTRIBUTES, new AttributesHandler()); resourceRegistration.registerReadOnlyAttribute(OPERATIONS, new OperationsHandler()); } static Resource.ResourceEntry createResource(AccessConstraintUtilization constraintUtilization) { return new AccessConstraintAppliesToResource(constraintUtilization); } private static class AccessConstraintAppliesToResource extends PlaceholderResource.PlaceholderResourceEntry { private final AccessConstraintUtilization constraintUtilization; private AccessConstraintAppliesToResource(AccessConstraintUtilization constraintUtilization) { super(PathElement.pathElement(ModelDescriptionConstants.APPLIES_TO, constraintUtilization.getPathAddress().toCLIStyleString())); this.constraintUtilization = constraintUtilization; } } private abstract static class AccessConstraintAppliesToHandler implements OperationStepHandler { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { AccessConstraintAppliesToResource resource = (AccessConstraintAppliesToResource) context.readResource(PathAddress.EMPTY_ADDRESS); setResult(context, resource.constraintUtilization); context.stepCompleted(); } abstract void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization); } private static class EntireResourceHandler extends AccessConstraintAppliesToHandler { @Override void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization) { context.getResult().set(constraintUtilization.isEntireResourceConstrained()); } } private abstract static class StringSetHandler extends AccessConstraintAppliesToHandler { @Override void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization) { ModelNode result = context.getResult(); result.setEmptyList(); for (String attribute : getStringSet(constraintUtilization)) { result.add(attribute); } } abstract Set<String> getStringSet(AccessConstraintUtilization constraintUtilization); } private static class AttributesHandler extends StringSetHandler { @Override Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { if (constraintUtilization.isEntireResourceConstrained()) { // Showing individual attributes is redundant and confusing return Collections.emptySet(); } return constraintUtilization.getAttributes(); } } private static class OperationsHandler extends StringSetHandler { @Override Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { if (constraintUtilization.isEntireResourceConstrained()) { // Showing individual operations is redundant and confusing return Collections.emptySet(); } return constraintUtilization.getOperations(); } } }
domain-management/src/main/java/org/jboss/as/domain/management/access/AccessConstraintAppliesToResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.domain.management.access; import java.util.Set; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReadResourceNameOperationStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleListAttributeDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.access.management.AccessConstraintUtilization; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.Resource; import org.jboss.as.domain.management._private.DomainManagementResolver; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * {@code ResourceDefinition} for the resources that expose what resources an * {@link org.jboss.as.controller.access.management.AccessConstraintDefinition} applies to. * * @author Brian Stansberry (c) 2013 Red Hat Inc. */ public class AccessConstraintAppliesToResourceDefinition extends SimpleResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(ModelDescriptionConstants.APPLIES_TO); public static final AttributeDefinition ADDRESS = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ADDRESS, ModelType.STRING).build(); public static final AttributeDefinition ENTIRE_RESOURCE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ENTIRE_RESOURCE, ModelType.BOOLEAN) .build(); public static final AttributeDefinition ATTRIBUTES = new SimpleListAttributeDefinition.Builder(ModelDescriptionConstants.ATTRIBUTES, new SimpleAttributeDefinitionBuilder("attribute", ModelType.STRING).build()) .build(); public static final AttributeDefinition OPERATIONS = new SimpleListAttributeDefinition.Builder(ModelDescriptionConstants.OPERATIONS, new SimpleAttributeDefinitionBuilder("operation", ModelType.STRING).build()) .build(); public AccessConstraintAppliesToResourceDefinition() { super(PATH_ELEMENT, DomainManagementResolver.getResolver("core.access-control.constraint.applies-to")); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(ADDRESS, ReadResourceNameOperationStepHandler.INSTANCE); resourceRegistration.registerReadOnlyAttribute(ENTIRE_RESOURCE, new EntireResourceHandler()); resourceRegistration.registerReadOnlyAttribute(ATTRIBUTES, new AttributesHandler()); resourceRegistration.registerReadOnlyAttribute(OPERATIONS, new OperationsHandler()); } static Resource.ResourceEntry createResource(AccessConstraintUtilization constraintUtilization) { return new AccessConstraintAppliesToResource(constraintUtilization); } private static class AccessConstraintAppliesToResource extends PlaceholderResource.PlaceholderResourceEntry { private final AccessConstraintUtilization constraintUtilization; private AccessConstraintAppliesToResource(AccessConstraintUtilization constraintUtilization) { super(PathElement.pathElement(ModelDescriptionConstants.APPLIES_TO, constraintUtilization.getPathAddress().toCLIStyleString())); this.constraintUtilization = constraintUtilization; } } private abstract static class AccessConstraintAppliesToHandler implements OperationStepHandler { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { AccessConstraintAppliesToResource resource = (AccessConstraintAppliesToResource) context.readResource(PathAddress.EMPTY_ADDRESS); setResult(context, resource.constraintUtilization); context.stepCompleted(); } abstract void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization); } private static class EntireResourceHandler extends AccessConstraintAppliesToHandler { @Override void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization) { context.getResult().set(constraintUtilization.isEntireResourceConstrained()); } } private abstract static class StringSetHandler extends AccessConstraintAppliesToHandler { @Override void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization) { ModelNode result = context.getResult(); result.setEmptyList(); for (String attribute : getStringSet(constraintUtilization)) { result.add(attribute); } } abstract Set<String> getStringSet(AccessConstraintUtilization constraintUtilization); } private static class AttributesHandler extends StringSetHandler { @Override Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { return constraintUtilization.getAttributes(); } } private static class OperationsHandler extends StringSetHandler { @Override Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { return constraintUtilization.getOperations(); } } }
Don't show redundant/confusing individual attribute/operation data in RBAC constraint applies-to if the entire resource is constrained
domain-management/src/main/java/org/jboss/as/domain/management/access/AccessConstraintAppliesToResourceDefinition.java
Don't show redundant/confusing individual attribute/operation data in RBAC constraint applies-to if the entire resource is constrained
<ide><path>omain-management/src/main/java/org/jboss/as/domain/management/access/AccessConstraintAppliesToResourceDefinition.java <ide> <ide> package org.jboss.as.domain.management.access; <ide> <add>import java.util.Collections; <ide> import java.util.Set; <ide> <ide> import org.jboss.as.controller.AttributeDefinition; <ide> <ide> @Override <ide> Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { <add> if (constraintUtilization.isEntireResourceConstrained()) { <add> // Showing individual attributes is redundant and confusing <add> return Collections.emptySet(); <add> } <ide> return constraintUtilization.getAttributes(); <ide> } <ide> } <ide> <ide> @Override <ide> Set<String> getStringSet(AccessConstraintUtilization constraintUtilization) { <add> if (constraintUtilization.isEntireResourceConstrained()) { <add> // Showing individual operations is redundant and confusing <add> return Collections.emptySet(); <add> } <ide> return constraintUtilization.getOperations(); <ide> } <ide> }
JavaScript
apache-2.0
3358f0ae85037847e8fb27238adb6006211fe3cd
0
google-github-actions/setup-gcloud,google-github-actions/setup-gcloud,google-github-actions/setup-gcloud
module.exports = /******/ (function(modules, runtime) { // webpackBootstrap /******/ "use strict"; /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ __webpack_require__.ab = __dirname + "/"; /******/ /******/ // the startup function /******/ function startup() { /******/ // Load entry module and return exports /******/ return __webpack_require__(738); /******/ }; /******/ /******/ // run startup /******/ return startup(); /******/ }) /************************************************************************/ /******/ ({ /***/ 1: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const childProcess = __webpack_require__(129); const path = __webpack_require__(622); const util_1 = __webpack_require__(669); const ioUtil = __webpack_require__(672); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. try { if (yield ioUtil.isDirectory(inputPath, true)) { yield exec(`rd /s /q "${inputPath}"`); } else { yield exec(`del /f /a "${inputPath}"`); } } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } // Shelling out fails to remove a symlink folder with missing source, this unlink catches that try { yield ioUtil.unlink(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } } else { let isDir = false; try { isDir = yield ioUtil.isDirectory(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; return; } if (isDir) { yield exec(`rm -rf "${inputPath}"`); } else { yield ioUtil.unlink(inputPath); } } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise<void> */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { yield ioUtil.mkdirP(fsPath); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise<string> path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } } try { // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { for (const extension of process.env.PATHEXT.split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return filePath; } return ''; } // if any path separators, return empty if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { return ''; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // return the first match for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); if (filePath) { return filePath; } } return ''; } catch (err) { throw new Error(`which failed with message ${err.message}`); } }); } exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); return { force, recursive }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 9: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __webpack_require__(87); const events = __webpack_require__(614); const child = __webpack_require__(129); const path = __webpack_require__(622); const io = __webpack_require__(1); const ioUtil = __webpack_require__(672); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); }); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 16: /***/ (function(module) { module.exports = require("tls"); /***/ }), /***/ 82: /***/ (function(__unusedmodule, exports) { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; //# sourceMappingURL=utils.js.map /***/ }), /***/ 86: /***/ (function(module, __unusedexports, __webpack_require__) { var rng = __webpack_require__(139); var bytesToUuid = __webpack_require__(722); // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [ seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] ]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); } module.exports = v1; /***/ }), /***/ 87: /***/ (function(module) { module.exports = require("os"); /***/ }), /***/ 102: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; // For internal use, subject to change. var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__webpack_require__(747)); const os = __importStar(__webpack_require__(87)); const utils_1 = __webpack_require__(82); function issueCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueCommand = issueCommand; //# sourceMappingURL=file-command.js.map /***/ }), /***/ 129: /***/ (function(module) { module.exports = require("child_process"); /***/ }), /***/ 139: /***/ (function(module, __unusedexports, __webpack_require__) { // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = __webpack_require__(417); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; /***/ }), /***/ 141: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var net = __webpack_require__(631); var tls = __webpack_require__(16); var http = __webpack_require__(605); var https = __webpack_require__(211); var events = __webpack_require__(614); var assert = __webpack_require__(357); var util = __webpack_require__(669); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 211: /***/ (function(module) { module.exports = require("https"); /***/ }), /***/ 357: /***/ (function(module) { module.exports = require("assert"); /***/ }), /***/ 413: /***/ (function(module, __unusedexports, __webpack_require__) { module.exports = __webpack_require__(141); /***/ }), /***/ 417: /***/ (function(module) { module.exports = require("crypto"); /***/ }), /***/ 431: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__webpack_require__(87)); const utils_1 = __webpack_require__(82); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 470: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const command_1 = __webpack_require__(431); const file_command_1 = __webpack_require__(102); const utils_1 = __webpack_require__(82); const os = __importStar(__webpack_require__(87)); const path = __importStar(__webpack_require__(622)); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = utils_1.toCommandValue(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { const delimiter = '_GitHubActionsFileCommandDelimeter_'; const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; file_command_1.issueCommand('ENV', commandValue); } else { command_1.issueCommand('set-env', { name }, convertedVal); } } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { file_command_1.issueCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } return val.trim(); } exports.getInput = getInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { command_1.issue('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() */ function error(message) { command_1.issue('error', message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds an warning issue * @param message warning issue message. Errors will be converted to string via toString() */ function warning(message) { command_1.issue('warning', message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; //# sourceMappingURL=core.js.map /***/ }), /***/ 533: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); const io = __importStar(__webpack_require__(1)); const fs = __importStar(__webpack_require__(747)); const os = __importStar(__webpack_require__(87)); const path = __importStar(__webpack_require__(622)); const httpm = __importStar(__webpack_require__(539)); const semver = __importStar(__webpack_require__(550)); const stream = __importStar(__webpack_require__(794)); const util = __importStar(__webpack_require__(669)); const v4_1 = __importDefault(__webpack_require__(826)); const exec_1 = __webpack_require__(986); const assert_1 = __webpack_require__(357); const retry_helper_1 = __webpack_require__(979); class HTTPError extends Error { constructor(httpStatusCode) { super(`Unexpected HTTP response: ${httpStatusCode}`); this.httpStatusCode = httpStatusCode; Object.setPrototypeOf(this, new.target.prototype); } } exports.HTTPError = HTTPError; const IS_WINDOWS = process.platform === 'win32'; const userAgent = 'actions/tool-cache'; /** * Download a tool from an url and stream it into a file * * @param url url of tool to download * @param dest path to download tool * @returns path to downloaded tool */ function downloadTool(url, dest) { return __awaiter(this, void 0, void 0, function* () { dest = dest || path.join(_getTempDirectory(), v4_1.default()); yield io.mkdirP(path.dirname(dest)); core.debug(`Downloading ${url}`); core.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { return yield downloadToolAttempt(url, dest || ''); }), (err) => { if (err instanceof HTTPError && err.httpStatusCode) { // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { return false; } } // Otherwise retry return true; }); }); } exports.downloadTool = downloadTool; function downloadToolAttempt(url, dest) { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } // Get the response headers const http = new httpm.HttpClient(userAgent, [], { allowRetries: false }); const response = yield http.get(url); if (response.message.statusCode !== 200) { const err = new HTTPError(response.message.statusCode); core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } // Download the response body const pipeline = util.promisify(stream.pipeline); const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); const readStream = responseMessageFactory(); let succeeded = false; try { yield pipeline(readStream, fs.createWriteStream(dest)); core.debug('download complete'); succeeded = true; return dest; } finally { // Error, delete dest before retry if (!succeeded) { core.debug('download failed'); try { yield io.rmRF(dest); } catch (err) { core.debug(`Failed to delete '${dest}'. ${err.message}`); } } } }); } /** * Extract a .7z file * * @param file path to the .7z file * @param dest destination directory. Optional. * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line * interface, it is smaller than the full command line interface, and it does support long paths. At the * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path * to 7zr.exe can be pass to this function. * @returns path to the destination directory */ function extract7z(file, dest, _7zPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); assert_1.ok(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); const originalCwd = process.cwd(); process.chdir(dest); if (_7zPath) { try { const args = [ 'x', '-bb1', '-bd', '-sccUTF-8', file ]; const options = { silent: true }; yield exec_1.exec(`"${_7zPath}"`, args, options); } finally { process.chdir(originalCwd); } } else { const escapedScript = path .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') .replace(/'/g, "''") .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; const options = { silent: true }; try { const powershellPath = yield io.which('powershell', true); yield exec_1.exec(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); } } return dest; }); } exports.extract7z = extract7z; /** * Extract a compressed tar archive * * @param file path to the tar * @param dest destination directory. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. * @returns path to the destination directory */ function extractTar(file, dest, flags = 'xz') { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } // Create dest dest = yield _createExtractFolder(dest); // Determine whether GNU tar core.debug('Checking tar --version'); let versionOutput = ''; yield exec_1.exec('tar --version', [], { ignoreReturnCode: true, silent: true, listeners: { stdout: (data) => (versionOutput += data.toString()), stderr: (data) => (versionOutput += data.toString()) } }); core.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); // Initialize args const args = [flags]; let destArg = dest; let fileArg = file; if (IS_WINDOWS && isGnuTar) { args.push('--force-local'); destArg = dest.replace(/\\/g, '/'); // Technically only the dest needs to have `/` but for aesthetic consistency // convert slashes in the file arg too. fileArg = file.replace(/\\/g, '/'); } if (isGnuTar) { // Suppress warnings when using GNU tar to extract archives created by BSD tar args.push('--warning=no-unknown-keyword'); } args.push('-C', destArg, '-f', fileArg); yield exec_1.exec(`tar`, args); return dest; }); } exports.extractTar = extractTar; /** * Extract a zip * * @param file path to the zip * @param dest destination directory. Optional. * @returns path to the destination directory */ function extractZip(file, dest) { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); if (IS_WINDOWS) { yield extractZipWin(file, dest); } else { yield extractZipNix(file, dest); } return dest; }); } exports.extractZip = extractZip; function extractZipWin(file, dest) { return __awaiter(this, void 0, void 0, function* () { // build the powershell command const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; // run powershell const powershellPath = yield io.which('powershell'); const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; yield exec_1.exec(`"${powershellPath}"`, args); }); } function extractZipNix(file, dest) { return __awaiter(this, void 0, void 0, function* () { const unzipPath = yield io.which('unzip'); yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest }); }); } /** * Caches a directory and installs it into the tool cacheDir * * @param sourceDir the directory to cache into tools * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheDir(sourceDir, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source dir: ${sourceDir}`); if (!fs.statSync(sourceDir).isDirectory()) { throw new Error('sourceDir is not a directory'); } // Create the tool dir const destPath = yield _createToolPath(tool, version, arch); // copy each child item. do not move. move can fail on Windows // due to anti-virus software having an open handle on a file. for (const itemName of fs.readdirSync(sourceDir)) { const s = path.join(sourceDir, itemName); yield io.cp(s, destPath, { recursive: true }); } // write .complete _completeToolPath(tool, version, arch); return destPath; }); } exports.cacheDir = cacheDir; /** * Caches a downloaded file (GUID) and installs it * into the tool cache with a given targetName * * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. * @param targetFile the name of the file name in the tools directory * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source file: ${sourceFile}`); if (!fs.statSync(sourceFile).isFile()) { throw new Error('sourceFile is not a file'); } // create the tool dir const destFolder = yield _createToolPath(tool, version, arch); // copy instead of move. move can fail on Windows due to // anti-virus software having an open handle on a file. const destPath = path.join(destFolder, targetFile); core.debug(`destination file ${destPath}`); yield io.cp(sourceFile, destPath); // write .complete _completeToolPath(tool, version, arch); return destFolder; }); } exports.cacheFile = cacheFile; /** * Finds the path to a tool version in the local installed tool cache * * @param toolName name of the tool * @param versionSpec version of the tool * @param arch optional arch. defaults to arch of computer */ function find(toolName, versionSpec, arch) { if (!toolName) { throw new Error('toolName parameter is required'); } if (!versionSpec) { throw new Error('versionSpec parameter is required'); } arch = arch || os.arch(); // attempt to resolve an explicit version if (!_isExplicitVersion(versionSpec)) { const localVersions = findAllVersions(toolName, arch); const match = _evaluateVersions(localVersions, versionSpec); versionSpec = match; } // check for the explicit version in the cache let toolPath = ''; if (versionSpec) { versionSpec = semver.clean(versionSpec) || ''; const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); core.debug(`checking cache: ${cachePath}`); if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); toolPath = cachePath; } else { core.debug('not found'); } } return toolPath; } exports.find = find; /** * Finds the paths to all versions of a tool that are installed in the local tool cache * * @param toolName name of the tool * @param arch optional arch. defaults to arch of computer */ function findAllVersions(toolName, arch) { const versions = []; arch = arch || os.arch(); const toolPath = path.join(_getCacheDirectory(), toolName); if (fs.existsSync(toolPath)) { const children = fs.readdirSync(toolPath); for (const child of children) { if (_isExplicitVersion(child)) { const fullPath = path.join(toolPath, child, arch || ''); if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { versions.push(child); } } } } return versions; } exports.findAllVersions = findAllVersions; function _createExtractFolder(dest) { return __awaiter(this, void 0, void 0, function* () { if (!dest) { // create a temp dir dest = path.join(_getTempDirectory(), v4_1.default()); } yield io.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); core.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io.rmRF(folderPath); yield io.rmRF(markerPath); yield io.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch) { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); const markerPath = `${folderPath}.complete`; fs.writeFileSync(markerPath, ''); core.debug('finished caching tool'); } function _isExplicitVersion(versionSpec) { const c = semver.clean(versionSpec) || ''; core.debug(`isExplicit: ${c}`); const valid = semver.valid(c) != null; core.debug(`explicit? ${valid}`); return valid; } function _evaluateVersions(versions, versionSpec) { let version = ''; core.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { if (semver.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; const satisfied = semver.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { core.debug(`matched: ${version}`); } else { core.debug('match not found'); } return version; } /** * Gets RUNNER_TOOL_CACHE */ function _getCacheDirectory() { const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); return cacheDirectory; } /** * Gets RUNNER_TEMP */ function _getTempDirectory() { const tempDirectory = process.env['RUNNER_TEMP'] || ''; assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); return tempDirectory; } /** * Gets a global variable */ function _getGlobal(key, defaultValue) { /* eslint-disable @typescript-eslint/no-explicit-any */ const value = global[key]; /* eslint-enable @typescript-eslint/no-explicit-any */ return value !== undefined ? value : defaultValue; } //# sourceMappingURL=tool-cache.js.map /***/ }), /***/ 539: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __webpack_require__(835); const http = __webpack_require__(605); const https = __webpack_require__(211); const pm = __webpack_require__(950); let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise(async (resolve, reject) => { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ async getJson(requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ async request(verb, requestUrl, data, headers) { if (this._disposed) { throw new Error('Client has already been disposed.'); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { await response.readBody(); await this._performExponentialBackoff(numTries); } } return response; } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { let parsedUrl = url.parse(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; let proxyUrl = pm.getProxyUrl(parsedUrl); let useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __webpack_require__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } static dateTimeDeserializer(key, value) { if (typeof value === 'string') { let a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } async _processResponse(res, options) { return new Promise(async (resolve, reject) => { const statusCode = res.message.statusCode; const response = { statusCode: statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response); } let obj; let contents; // get the result from the body try { contents = await res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = 'Failed request: (' + statusCode + ')'; } let err = new Error(msg); // attach statusCode and body obj (if available) to the error object err['statusCode'] = statusCode; if (response.result) { err['result'] = response.result; } reject(err); } else { resolve(response); } }); } } exports.HttpClient = HttpClient; /***/ }), /***/ 550: /***/ (function(module, exports) { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 605: /***/ (function(module) { module.exports = require("http"); /***/ }), /***/ 614: /***/ (function(module) { module.exports = require("events"); /***/ }), /***/ 622: /***/ (function(module) { module.exports = require("path"); /***/ }), /***/ 631: /***/ (function(module) { module.exports = require("net"); /***/ }), /***/ 669: /***/ (function(module) { module.exports = require("util"); /***/ }), /***/ 672: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); const assert_1 = __webpack_require__(357); const fs = __webpack_require__(747); const path = __webpack_require__(622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Recursively create a directory at `fsPath`. * * This implementation is optimistic, meaning it attempts to create the full * path first, and backs up the path stack from there. * * @param fsPath The path to create * @param maxDepth The maximum recursion depth * @param depth The current recursion depth */ function mkdirP(fsPath, maxDepth = 1000, depth = 1) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); fsPath = path.resolve(fsPath); if (depth >= maxDepth) return exports.mkdir(fsPath); try { yield exports.mkdir(fsPath); return; } catch (err) { switch (err.code) { case 'ENOENT': { yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); yield exports.mkdir(fsPath); return; } default: { let stats; try { stats = yield exports.stat(fsPath); } catch (err2) { throw err; } if (!stats.isDirectory()) throw err; } } } }); } exports.mkdirP = mkdirP; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } //# sourceMappingURL=io-util.js.map /***/ }), /***/ 702: /***/ (function(module, __unusedexports, __webpack_require__) { module.exports = /******/ (function(modules, runtime) { // webpackBootstrap /******/ "use strict"; /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ __webpack_require__.ab = __dirname + "/"; /******/ /******/ // the startup function /******/ function startup() { /******/ // Load entry module and return exports /******/ return __webpack_require__(325); /******/ }; /******/ /******/ // run startup /******/ return startup(); /******/ }) /************************************************************************/ /******/ ({ /***/ 1: /***/ (function(__unusedmodule, exports, __nested_webpack_require_1416__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const childProcess = __nested_webpack_require_1416__(129); const path = __nested_webpack_require_1416__(622); const util_1 = __nested_webpack_require_1416__(669); const ioUtil = __nested_webpack_require_1416__(672); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. try { if (yield ioUtil.isDirectory(inputPath, true)) { yield exec(`rd /s /q "${inputPath}"`); } else { yield exec(`del /f /a "${inputPath}"`); } } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } // Shelling out fails to remove a symlink folder with missing source, this unlink catches that try { yield ioUtil.unlink(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } } else { let isDir = false; try { isDir = yield ioUtil.isDirectory(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; return; } if (isDir) { yield exec(`rm -rf "${inputPath}"`); } else { yield ioUtil.unlink(inputPath); } } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise<void> */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { yield ioUtil.mkdirP(fsPath); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise<string> path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } } try { // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { for (const extension of process.env.PATHEXT.split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return filePath; } return ''; } // if any path separators, return empty if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { return ''; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // return the first match for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); if (filePath) { return filePath; } } return ''; } catch (err) { throw new Error(`which failed with message ${err.message}`); } }); } exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); return { force, recursive }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 8: /***/ (function(__unusedmodule, exports, __nested_webpack_require_13050__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const httpm = __importStar(__nested_webpack_require_13050__(874)); const attempt_1 = __nested_webpack_require_13050__(503); const install_util_1 = __nested_webpack_require_13050__(962); /** * Formats the gcloud SDK release URL according to the specified arguments. * * @param os The OS of the requested release. * @param arch The system architecture of the requested release. * @param version The version of the requested release. * @returns The formatted gcloud SDK release URL. */ function formatReleaseURL(os, arch, version) { // massage the arch to match gcloud sdk conventions if (arch == 'x64') { arch = 'x86_64'; } let objectName; switch (os) { case 'linux': objectName = `google-cloud-sdk-${version}-linux-${arch}.tar.gz`; break; case 'darwin': objectName = `google-cloud-sdk-${version}-darwin-${arch}.tar.gz`; break; case 'win32': objectName = `google-cloud-sdk-${version}-windows-${arch}.zip`; break; default: throw new Error(`Unexpected OS '${os}'`); } return encodeURI(`https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/${objectName}`); } /** * Creates the gcloud SDK release URL for the specified arguments, verifying * its existence. * * @param os The OS of the requested release. * @param arch The system architecture of the requested release. * @param version The version of the requested release. * @returns The verified gcloud SDK release URL. */ function getReleaseURL(os, arch, version) { return __awaiter(this, void 0, void 0, function* () { try { const url = formatReleaseURL(os, arch, version); const client = new httpm.HttpClient(install_util_1.GCLOUD_METRICS_LABEL); return attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { const res = yield client.head(url); if (res.message.statusCode === 200) { return url; } else { throw new Error(`error code: ${res.message.statusCode}`); } }), { delay: 200, factor: 2, maxAttempts: 4, }); } catch (err) { throw new Error(`Error trying to get gcloud SDK release URL: os: ${os} arch: ${arch} version: ${version}, err: ${err}`); } }); } exports.getReleaseURL = getReleaseURL; /***/ }), /***/ 9: /***/ (function(__unusedmodule, exports, __nested_webpack_require_17245__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__nested_webpack_require_17245__(87)); const events = __importStar(__nested_webpack_require_17245__(614)); const child = __importStar(__nested_webpack_require_17245__(129)); const path = __importStar(__nested_webpack_require_17245__(622)); const io = __importStar(__nested_webpack_require_17245__(1)); const ioUtil = __importStar(__nested_webpack_require_17245__(672)); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } }); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 11: /***/ (function(module) { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 13: /***/ (function(module, __unusedexports, __nested_webpack_require_42639__) { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; var util = __nested_webpack_require_42639__(581); var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = util.assign( { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } } }, Format ); /***/ }), /***/ 16: /***/ (function(module) { module.exports = __webpack_require__(16); /***/ }), /***/ 49: /***/ (function(module, __unusedexports, __nested_webpack_require_43337__) { var wrappy = __nested_webpack_require_43337__(11) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 71: /***/ (function(__unusedmodule, exports, __nested_webpack_require_44366__) { "use strict"; /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * Contains version utility functions. */ const httpm = __importStar(__nested_webpack_require_44366__(874)); const attempt_1 = __nested_webpack_require_44366__(503); const install_util_1 = __nested_webpack_require_44366__(962); /** * @returns The latest stable version of the gcloud SDK. */ function getLatestGcloudSDKVersion() { return __awaiter(this, void 0, void 0, function* () { const queryUrl = 'https://dl.google.com/dl/cloudsdk/channels/rapid/components-2.json'; const client = new httpm.HttpClient(install_util_1.GCLOUD_METRICS_LABEL); return yield attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { const res = yield client.get(queryUrl); if (res.message.statusCode != 200) { throw new Error(`Failed to retrieve gcloud SDK version, HTTP error code: ${res.message.statusCode} url: ${queryUrl}`); } const body = yield res.readBody(); const responseObject = JSON.parse(body); if (!responseObject.version) { throw new Error(`Failed to retrieve gcloud SDK version, invalid response body: ${body}`); } return responseObject.version; }), { delay: 200, factor: 2, maxAttempts: 4, }); }); } exports.getLatestGcloudSDKVersion = getLatestGcloudSDKVersion; /***/ }), /***/ 87: /***/ (function(module) { module.exports = __webpack_require__(87); /***/ }), /***/ 93: /***/ (function(module, __unusedexports, __nested_webpack_require_47523__) { module.exports = minimatch minimatch.Minimatch = Minimatch var path = { sep: '/' } try { path = __nested_webpack_require_47523__(622) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nested_webpack_require_47523__(306) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {} b = b || {} var t = {} Object.keys(b).forEach(function (k) { t[k] = b[k] }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = console.error this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { case '/': // completely not allowed, even escaped. // Should already be path-split by now. return false case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:<pattern>)<type> re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '.': case '[': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { hit = f === p } this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') return emptyFileEnd } // should be unreachable. throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 117: /***/ (function(__unusedmodule, exports, __nested_webpack_require_72966__) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __nested_webpack_require_72966__(622); var isWindows = process.platform === 'win32'; var fs = __nested_webpack_require_72966__(747); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 129: /***/ (function(module) { module.exports = __webpack_require__(129); /***/ }), /***/ 139: /***/ (function(module, __unusedexports, __nested_webpack_require_81710__) { // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = __nested_webpack_require_81710__(417); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; /***/ }), /***/ 141: /***/ (function(__unusedmodule, exports, __nested_webpack_require_82052__) { "use strict"; var net = __nested_webpack_require_82052__(631); var tls = __nested_webpack_require_82052__(16); var http = __nested_webpack_require_82052__(605); var https = __nested_webpack_require_82052__(211); var events = __nested_webpack_require_82052__(614); var assert = __nested_webpack_require_82052__(357); var util = __nested_webpack_require_82052__(669); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 150: /***/ (function(module, __unusedexports, __nested_webpack_require_89829__) { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan <[email protected]> * * MIT Licensed */ /* * Module dependencies. */ const fs = __nested_webpack_require_89829__(747); const os = __nested_webpack_require_89829__(87); const path = __nested_webpack_require_89829__(622); const crypto = __nested_webpack_require_89829__(417); const _c = fs.constants && os.constants ? { fs: fs.constants, os: os.constants } : process.binding('constants'); const rimraf = __nested_webpack_require_89829__(569); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, EXIT = 'exit', SIGINT = 'SIGINT', // this will hold the objects need to be removed on exit _removeObjects = []; var _gracefulCleanup = false; /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { var value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|Function)} options * @param {Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } return [options, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = _getTmpDir(); // fail early on missing tmp dir if (isBlank(opts.dir) && isBlank(tmpDir)) { throw new Error('No tmp dir specified'); } /* istanbul ignore else */ if (!isBlank(opts.name)) { return path.join(opts.dir || tmpDir, opts.name); } // mkstemps like template // opts.template has already been guarded in tmpName() below /* istanbul ignore else */ if (opts.template) { var template = opts.template; // make sure that we prepend the tmp path if none was given /* istanbul ignore else */ if (path.basename(template) === template) template = path.join(opts.dir || tmpDir, template); return template.replace(TEMPLATE_PATTERN, _randomChars(6)); } // prefix and postfix const name = [ (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), process.pid, _randomChars(12), (opts.postfix ? opts.postfix : '') ].join(''); return path.join(opts.dir || tmpDir, name); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) return cb(new Error('Invalid tries')); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) return cb(new Error('Invalid template provided')); (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { var args = _parseArguments(options), opts = args[0], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) throw new Error('Invalid tries'); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) throw new Error('Invalid template provided'); do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|fileCallback)} options the config options or the callback function * @param {?fileCallback} callback */ function file(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbul ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(err) { /* istanbul ignore else */ if (err) { // Low probability, and the file exists, so this could be // ignored. If it isn't we certainly need to unlink the // file, and if that fails too its error is more // important. try { fs.unlinkSync(name); } catch (e) { if (!isENOENT(e)) { err = e; } } return cb(err); } cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); }); } /* istanbul ignore else */ if (opts.detachDescriptor) { return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); } cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { var args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { var args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); } if (0 <= fdPath[0]) fs.close(fdPath[0], function (err) { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!isEBADF(e) && !isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!isENOENT(e)) throw e; } } } /** * Prepares the callback for removal of the temporary file. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @returns {fileCallback} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Simple wrapper for rimraf. * * @param {string} dirPath * @param {Function} next * @private */ function _rimrafRemoveDirWrapper(dirPath, next) { rimraf(dirPath, next); } /** * Simple wrapper for rimraf.sync. * * @param {string} dirPath * @private */ function _rimrafRemoveDirSyncWrapper(dirPath, next) { try { return next(null, rimraf.sync(dirPath)); } catch (err) { return next(err); } } /** * Prepares the callback for removal of the temporary directory. * * @param {string} name * @param {Object} opts * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts) { const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * @param {Function} removeFunction * @param {Object} arg * @returns {Function} * @private */ function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { var called = false; return function _cleanupCallback(next) { next = next || function () {}; if (!called) { const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; // sync? if (removeFunction.length === 1) { try { removeFunction(arg); return next(null); } catch (err) { // if no next is provided and since we are // in silent cleanup mode on process exit, // we will ignore the error return next(err); } } else return removeFunction(arg, next); } else return next(new Error('cleanup callback has already been called')); }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. */ function isEBADF(error) { return isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. */ function isENOENT(error) { return isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {string|number} any numerical value will be negated * * - Node >= 6.0 < 7.0: * error.code {string} * error.errno {number} negated * * - Node >= 4.0 < 6.0: introduces SystemError * error.code {string} * error.errno {number} negated * * - Node >= 0.10 < 4.0: * error.code {number} negated * error.errno n/a */ function isExpectedError(error, code, errno) { return error.code === code || error.code === errno; } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function isBlank(s) { return s === null || s === undefined || !s.trim(); } /** * Sets the graceful cleanup. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @returns {string} the currently configured tmp dir */ function _getTmpDir() { return os.tmpdir(); } /** * If there are multiple different versions of tmp in place, make sure that * we recognize the old listeners. * * @param {Function} listener * @private * @returns {Boolean} true whether listener is a legacy listener */ function _is_legacy_listener(listener) { return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') && listener.toString().indexOf('_garbageCollector();') > -1; } /** * Safely install SIGINT listener. * * NOTE: this will only work on OSX and Linux. * * @private */ function _safely_install_sigint_listener() { const listeners = process.listeners(SIGINT); const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ if (lstnr.name === '_tmp$sigint_listener') { existingListeners.push(lstnr); process.removeListener(SIGINT, lstnr); } } process.on(SIGINT, function _tmp$sigint_listener(doExit) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](false); } catch (err) { // ignore } } try { // force the garbage collector even it is called again in the exit listener _garbageCollector(); } finally { if (!!doExit) { process.exit(0); } } }); } /** * Safely install process exit listener. * * @private */ function _safely_install_exit_listener() { const listeners = process.listeners(EXIT); // collect any existing listeners const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ // TODO: remove support for legacy listeners once release 1.0.0 is out if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { // we must forget about the uncaughtException listener, hopefully it is ours if (lstnr.name !== '_uncaughtExceptionThrown') { existingListeners.push(lstnr); } process.removeListener(EXIT, lstnr); } } // TODO: what was the data parameter good for? process.addListener(EXIT, function _tmp$safe_listener(data) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](data); } catch (err) { // ignore } } _garbageCollector(); }); } _safely_install_exit_listener(); _safely_install_sigint_listener(); /** * Configuration options. * * @typedef {Object} Options * @property {?number} tries the number of tries before give up the name generation * @property {?string} template the "mkstemp" like filename template * @property {?string} name fix name * @property {?string} dir the tmp directory to use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call after entry was removed */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, 'tmpdir', { enumerable: true, configurable: false, get: function () { return _getTmpDir(); } }); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 211: /***/ (function(module) { module.exports = __webpack_require__(211); /***/ }), /***/ 245: /***/ (function(module, __unusedexports, __nested_webpack_require_109664__) { module.exports = globSync globSync.GlobSync = GlobSync var fs = __nested_webpack_require_109664__(747) var rp = __nested_webpack_require_109664__(302) var minimatch = __nested_webpack_require_109664__(93) var Minimatch = minimatch.Minimatch var Glob = __nested_webpack_require_109664__(402).Glob var util = __nested_webpack_require_109664__(669) var path = __nested_webpack_require_109664__(622) var assert = __nested_webpack_require_109664__(357) var isAbsolute = __nested_webpack_require_109664__(681) var common = __nested_webpack_require_109664__(856) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 280: /***/ (function(module, exports) { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 302: /***/ (function(module, __unusedexports, __nested_webpack_require_163989__) { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nested_webpack_require_163989__(747) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nested_webpack_require_163989__(117) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 306: /***/ (function(module, __unusedexports, __nested_webpack_require_165402__) { var concatMap = __nested_webpack_require_165402__(896); var balanced = __nested_webpack_require_165402__(621); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 315: /***/ (function(module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 325: /***/ (function(__unusedmodule, exports, __nested_webpack_require_171089__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const exec = __importStar(__nested_webpack_require_171089__(986)); const toolCache = __importStar(__nested_webpack_require_171089__(533)); const os = __importStar(__nested_webpack_require_171089__(87)); const tmp = __importStar(__nested_webpack_require_171089__(150)); const format_url_1 = __nested_webpack_require_171089__(8); const downloadUtil = __importStar(__nested_webpack_require_171089__(339)); const installUtil = __importStar(__nested_webpack_require_171089__(962)); const version_util_1 = __nested_webpack_require_171089__(71); exports.getLatestGcloudSDKVersion = version_util_1.getLatestGcloudSDKVersion; /** * Checks if gcloud is installed. * * @param version (Optional) Cloud SDK version. * @return true if gcloud is found in toolpath. */ function isInstalled(version) { let toolPath; if (version) { toolPath = toolCache.find('gcloud', version); return toolPath != undefined && toolPath !== ''; } else { toolPath = toolCache.findAllVersions('gcloud'); return toolPath.length > 0; } } exports.isInstalled = isInstalled; /** * Returns the correct gcloud command for OS. * * @returns gcloud command. */ function getToolCommand() { // A workaround for https://github.com/actions/toolkit/issues/229 // Currently exec on windows runs as cmd shell. let toolCommand = 'gcloud'; if (process.platform == 'win32') { toolCommand = 'gcloud.cmd'; } return toolCommand; } exports.getToolCommand = getToolCommand; /** * Checks if the project Id is set in the gcloud config. * * @returns true is project Id is set. */ function isProjectIdSet() { return __awaiter(this, void 0, void 0, function* () { // stdout captures project id let output = ''; const stdout = (data) => { output += data.toString(); }; // stderr captures "(unset)" let errOutput = ''; const stderr = (data) => { errOutput += data.toString(); }; const options = { listeners: { stdout, stderr, }, }; const toolCommand = getToolCommand(); yield exec.exec(toolCommand, ['config', 'get-value', 'project'], options); return !(output.includes('unset') || errOutput.includes('unset')); }); } exports.isProjectIdSet = isProjectIdSet; /** * Checks if gcloud is authenticated. * * @returns true is gcloud is authenticated. */ function isAuthenticated() { return __awaiter(this, void 0, void 0, function* () { let output = ''; const stdout = (data) => { output += data.toString(); }; const options = { listeners: { stdout, }, }; const toolCommand = getToolCommand(); yield exec.exec(toolCommand, ['auth', 'list'], options); return !output.includes('No credentialed accounts.'); }); } exports.isAuthenticated = isAuthenticated; /** * Installs the gcloud SDK into the actions environment. * * @param version The version being installed. * @returns The path of the installed tool. */ function installGcloudSDK(version) { return __awaiter(this, void 0, void 0, function* () { // Retreive the release corresponding to the specified version and OS const osPlat = os.platform(); const osArch = os.arch(); const url = yield format_url_1.getReleaseURL(osPlat, osArch, version); // Download and extract the release const extPath = yield downloadUtil.downloadAndExtractTool(url); if (!extPath) { throw new Error(`Failed to download release, url: ${url}`); } // Install the downloaded release into the github action env return yield installUtil.installGcloudSDK(version, extPath); }); } exports.installGcloudSDK = installGcloudSDK; /** * Parses the service account string into JSON. * * @param serviceAccountKey The service account key used for authentication. * @returns ServiceAccountKey as an object. */ function parseServiceAccountKey(serviceAccountKey) { let serviceAccount = serviceAccountKey; // Handle base64-encoded credentials if (!serviceAccountKey.trim().startsWith('{')) { serviceAccount = Buffer.from(serviceAccountKey, 'base64').toString('utf8'); } return JSON.parse(serviceAccount); } exports.parseServiceAccountKey = parseServiceAccountKey; /** * Authenticates the gcloud tool using a service account key. * * @param serviceAccountKey The service account key used for authentication. * @returns exit code. */ function authenticateGcloudSDK(serviceAccountKey) { return __awaiter(this, void 0, void 0, function* () { tmp.setGracefulCleanup(); const serviceAccountJson = parseServiceAccountKey(serviceAccountKey); const serviceAccountEmail = serviceAccountJson.client_email; const toolCommand = getToolCommand(); // Authenticate as the specified service account. const options = { input: Buffer.from(JSON.stringify(serviceAccountJson)) }; return yield exec.exec(toolCommand, [ '--quiet', 'auth', 'activate-service-account', serviceAccountEmail, '--key-file', '-', ], options); }); } exports.authenticateGcloudSDK = authenticateGcloudSDK; /** * Sets the GCP Project Id in the gcloud config. * * @param serviceAccountKey The service account key used for authentication. * @returns project ID. */ function setProject(projectId) { return __awaiter(this, void 0, void 0, function* () { const toolCommand = getToolCommand(); return yield exec.exec(toolCommand, [ '--quiet', 'config', 'set', 'project', projectId, ]); }); } exports.setProject = setProject; /** * Sets the GCP Project Id in the gcloud config. * * @param serviceAccountKey The service account key used for authentication. * @returns project ID. */ function setProjectWithKey(serviceAccountKey) { return __awaiter(this, void 0, void 0, function* () { const serviceAccountJson = parseServiceAccountKey(serviceAccountKey); yield setProject(serviceAccountJson.project_id); return serviceAccountJson.project_id; }); } exports.setProjectWithKey = setProjectWithKey; /***/ }), /***/ 339: /***/ (function(__unusedmodule, exports, __nested_webpack_require_179112__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * Contains download utility functions. */ const toolCache = __importStar(__nested_webpack_require_179112__(533)); const attempt_1 = __nested_webpack_require_179112__(503); /** * Downloads and extracts the tool at the specified URL. * * @url The URL of the tool to be downloaded. * @returns The path to the locally extracted tool. */ function downloadAndExtractTool(url) { return __awaiter(this, void 0, void 0, function* () { const downloadPath = yield attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { return toolCache.downloadTool(url); }), { delay: 200, factor: 2, maxAttempts: 4, }); let extractedPath; if (url.indexOf('.zip') != -1) { extractedPath = yield toolCache.extractZip(downloadPath); } else if (url.indexOf('.tar.gz') != -1) { extractedPath = yield toolCache.extractTar(downloadPath); } else if (url.indexOf('.7z') != -1) { extractedPath = yield toolCache.extract7z(downloadPath); } else { throw new Error(`Unexpected download archive type, downloadPath: ${downloadPath}`); } return extractedPath; }); } exports.downloadAndExtractTool = downloadAndExtractTool; /***/ }), /***/ 357: /***/ (function(module) { module.exports = __webpack_require__(357); /***/ }), /***/ 386: /***/ (function(module, __unusedexports, __nested_webpack_require_182187__) { "use strict"; var stringify = __nested_webpack_require_182187__(897); var parse = __nested_webpack_require_182187__(755); var formats = __nested_webpack_require_182187__(13); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /***/ 402: /***/ (function(module, __unusedexports, __nested_webpack_require_182499__) { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var fs = __nested_webpack_require_182499__(747) var rp = __nested_webpack_require_182499__(302) var minimatch = __nested_webpack_require_182499__(93) var Minimatch = minimatch.Minimatch var inherits = __nested_webpack_require_182499__(689) var EE = __nested_webpack_require_182499__(614).EventEmitter var path = __nested_webpack_require_182499__(622) var assert = __nested_webpack_require_182499__(357) var isAbsolute = __nested_webpack_require_182499__(681) var globSync = __nested_webpack_require_182499__(245) var common = __nested_webpack_require_182499__(856) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __nested_webpack_require_182499__(674) var util = __nested_webpack_require_182499__(669) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nested_webpack_require_182499__(49) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 413: /***/ (function(module, __unusedexports, __nested_webpack_require_202090__) { module.exports = __nested_webpack_require_202090__(141); /***/ }), /***/ 417: /***/ (function(module) { module.exports = __webpack_require__(417); /***/ }), /***/ 431: /***/ (function(__unusedmodule, exports, __nested_webpack_require_202308__) { "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__nested_webpack_require_202308__(87)); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return (s || '') .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return (s || '') .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 470: /***/ (function(__unusedmodule, exports, __nested_webpack_require_204755__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const command_1 = __nested_webpack_require_204755__(431); const os = __importStar(__nested_webpack_require_204755__(87)); const path = __importStar(__nested_webpack_require_204755__(622)); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable */ function exportVariable(name, val) { process.env[name] = val; command_1.issueCommand('set-env', { name }, val); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { command_1.issueCommand('add-path', {}, inputPath); process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } return val.trim(); } exports.getInput = getInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store */ function setOutput(name, value) { command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message */ function error(message) { command_1.issue('error', message); } exports.error = error; /** * Adds an warning issue * @param message warning issue message */ function warning(message) { command_1.issue('warning', message); } exports.warning = warning; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store */ function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; //# sourceMappingURL=core.js.map /***/ }), /***/ 503: /***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function applyDefaults(options) { if (!options) { options = {}; } return { delay: (options.delay === undefined) ? 200 : options.delay, initialDelay: (options.initialDelay === undefined) ? 0 : options.initialDelay, minDelay: (options.minDelay === undefined) ? 0 : options.minDelay, maxDelay: (options.maxDelay === undefined) ? 0 : options.maxDelay, factor: (options.factor === undefined) ? 0 : options.factor, maxAttempts: (options.maxAttempts === undefined) ? 3 : options.maxAttempts, timeout: (options.timeout === undefined) ? 0 : options.timeout, jitter: (options.jitter === true), handleError: (options.handleError === undefined) ? null : options.handleError, handleTimeout: (options.handleTimeout === undefined) ? null : options.handleTimeout, beforeAttempt: (options.beforeAttempt === undefined) ? null : options.beforeAttempt, calculateDelay: (options.calculateDelay === undefined) ? null : options.calculateDelay }; } async function sleep(delay) { return new Promise((resolve, reject) => { setTimeout(resolve, delay); }); } exports.sleep = sleep; function defaultCalculateDelay(context, options) { let delay = options.delay; if (delay === 0) { // no delay between attempts return 0; } if (options.factor) { delay *= Math.pow(options.factor, context.attemptNum - 1); if (options.maxDelay !== 0) { delay = Math.min(delay, options.maxDelay); } } if (options.jitter) { // Jitter will result in a random value between `minDelay` and // calculated delay for a given attempt. // See https://www.awsarchitectureblog.com/2015/03/backoff.html // We're using the "full jitter" strategy. const min = Math.ceil(options.minDelay); const max = Math.floor(delay); delay = Math.floor(Math.random() * (max - min + 1)) + min; } return Math.round(delay); } exports.defaultCalculateDelay = defaultCalculateDelay; async function retry(attemptFunc, attemptOptions) { const options = applyDefaults(attemptOptions); for (const prop of [ 'delay', 'initialDelay', 'minDelay', 'maxDelay', 'maxAttempts', 'timeout' ]) { const value = options[prop]; if (!Number.isInteger(value) || (value < 0)) { throw new Error(`Value for ${prop} must be an integer greater than or equal to 0`); } } if ((options.factor.constructor !== Number) || (options.factor < 0)) { throw new Error(`Value for factor must be a number greater than or equal to 0`); } if (options.delay < options.minDelay) { throw new Error(`delay cannot be less than minDelay (delay: ${options.delay}, minDelay: ${options.minDelay}`); } const context = { attemptNum: 0, attemptsRemaining: options.maxAttempts ? options.maxAttempts : -1, aborted: false, abort() { context.aborted = true; } }; const calculateDelay = options.calculateDelay || defaultCalculateDelay; async function makeAttempt() { if (options.beforeAttempt) { options.beforeAttempt(context, options); } if (context.aborted) { const err = new Error(`Attempt aborted`); err.code = 'ATTEMPT_ABORTED'; throw err; } const onError = async (err) => { if (options.handleError) { options.handleError(err, context, options); } if (context.aborted || (context.attemptsRemaining === 0)) { throw err; } // We are about to try again so increment attempt number context.attemptNum++; const delay = calculateDelay(context, options); if (delay) { await sleep(delay); } return makeAttempt(); }; if (context.attemptsRemaining > 0) { context.attemptsRemaining--; } if (options.timeout) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { if (options.handleTimeout) { resolve(options.handleTimeout(context, options)); } else { const err = new Error(`Retry timeout (attemptNum: ${context.attemptNum}, timeout: ${options.timeout})`); err.code = 'ATTEMPT_TIMEOUT'; reject(err); } }, options.timeout); attemptFunc(context, options).then((result) => { clearTimeout(timer); resolve(result); }).catch((err) => { clearTimeout(timer); resolve(onError(err)); }); }); } else { // No timeout provided so wait indefinitely for the returned promise // to be resolved. return attemptFunc(context, options).catch(onError); } } const initialDelay = options.calculateDelay ? options.calculateDelay(context, options) : options.initialDelay; if (initialDelay) { await sleep(initialDelay); } return makeAttempt(); } exports.retry = retry; /***/ }), /***/ 533: /***/ (function(__unusedmodule, exports, __nested_webpack_require_216825__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__nested_webpack_require_216825__(470)); const io = __importStar(__nested_webpack_require_216825__(1)); const fs = __importStar(__nested_webpack_require_216825__(747)); const os = __importStar(__nested_webpack_require_216825__(87)); const path = __importStar(__nested_webpack_require_216825__(622)); const httpm = __importStar(__nested_webpack_require_216825__(539)); const semver = __importStar(__nested_webpack_require_216825__(280)); const stream = __importStar(__nested_webpack_require_216825__(794)); const util = __importStar(__nested_webpack_require_216825__(669)); const v4_1 = __importDefault(__nested_webpack_require_216825__(826)); const exec_1 = __nested_webpack_require_216825__(986); const assert_1 = __nested_webpack_require_216825__(357); const retry_helper_1 = __nested_webpack_require_216825__(979); class HTTPError extends Error { constructor(httpStatusCode) { super(`Unexpected HTTP response: ${httpStatusCode}`); this.httpStatusCode = httpStatusCode; Object.setPrototypeOf(this, new.target.prototype); } } exports.HTTPError = HTTPError; const IS_WINDOWS = process.platform === 'win32'; const userAgent = 'actions/tool-cache'; /** * Download a tool from an url and stream it into a file * * @param url url of tool to download * @param dest path to download tool * @returns path to downloaded tool */ function downloadTool(url, dest) { return __awaiter(this, void 0, void 0, function* () { dest = dest || path.join(_getTempDirectory(), v4_1.default()); yield io.mkdirP(path.dirname(dest)); core.debug(`Downloading ${url}`); core.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { return yield downloadToolAttempt(url, dest || ''); }), (err) => { if (err instanceof HTTPError && err.httpStatusCode) { // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { return false; } } // Otherwise retry return true; }); }); } exports.downloadTool = downloadTool; function downloadToolAttempt(url, dest) { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } // Get the response headers const http = new httpm.HttpClient(userAgent, [], { allowRetries: false }); const response = yield http.get(url); if (response.message.statusCode !== 200) { const err = new HTTPError(response.message.statusCode); core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } // Download the response body const pipeline = util.promisify(stream.pipeline); const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); const readStream = responseMessageFactory(); let succeeded = false; try { yield pipeline(readStream, fs.createWriteStream(dest)); core.debug('download complete'); succeeded = true; return dest; } finally { // Error, delete dest before retry if (!succeeded) { core.debug('download failed'); try { yield io.rmRF(dest); } catch (err) { core.debug(`Failed to delete '${dest}'. ${err.message}`); } } } }); } /** * Extract a .7z file * * @param file path to the .7z file * @param dest destination directory. Optional. * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line * interface, it is smaller than the full command line interface, and it does support long paths. At the * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path * to 7zr.exe can be pass to this function. * @returns path to the destination directory */ function extract7z(file, dest, _7zPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); assert_1.ok(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); const originalCwd = process.cwd(); process.chdir(dest); if (_7zPath) { try { const args = [ 'x', '-bb1', '-bd', '-sccUTF-8', file ]; const options = { silent: true }; yield exec_1.exec(`"${_7zPath}"`, args, options); } finally { process.chdir(originalCwd); } } else { const escapedScript = path .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') .replace(/'/g, "''") .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; const options = { silent: true }; try { const powershellPath = yield io.which('powershell', true); yield exec_1.exec(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); } } return dest; }); } exports.extract7z = extract7z; /** * Extract a compressed tar archive * * @param file path to the tar * @param dest destination directory. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. * @returns path to the destination directory */ function extractTar(file, dest, flags = 'xz') { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } // Create dest dest = yield _createExtractFolder(dest); // Determine whether GNU tar core.debug('Checking tar --version'); let versionOutput = ''; yield exec_1.exec('tar --version', [], { ignoreReturnCode: true, silent: true, listeners: { stdout: (data) => (versionOutput += data.toString()), stderr: (data) => (versionOutput += data.toString()) } }); core.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); // Initialize args const args = [flags]; let destArg = dest; let fileArg = file; if (IS_WINDOWS && isGnuTar) { args.push('--force-local'); destArg = dest.replace(/\\/g, '/'); // Technically only the dest needs to have `/` but for aesthetic consistency // convert slashes in the file arg too. fileArg = file.replace(/\\/g, '/'); } if (isGnuTar) { // Suppress warnings when using GNU tar to extract archives created by BSD tar args.push('--warning=no-unknown-keyword'); } args.push('-C', destArg, '-f', fileArg); yield exec_1.exec(`tar`, args); return dest; }); } exports.extractTar = extractTar; /** * Extract a zip * * @param file path to the zip * @param dest destination directory. Optional. * @returns path to the destination directory */ function extractZip(file, dest) { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); if (IS_WINDOWS) { yield extractZipWin(file, dest); } else { yield extractZipNix(file, dest); } return dest; }); } exports.extractZip = extractZip; function extractZipWin(file, dest) { return __awaiter(this, void 0, void 0, function* () { // build the powershell command const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; // run powershell const powershellPath = yield io.which('powershell'); const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; yield exec_1.exec(`"${powershellPath}"`, args); }); } function extractZipNix(file, dest) { return __awaiter(this, void 0, void 0, function* () { const unzipPath = yield io.which('unzip'); yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest }); }); } /** * Caches a directory and installs it into the tool cacheDir * * @param sourceDir the directory to cache into tools * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheDir(sourceDir, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source dir: ${sourceDir}`); if (!fs.statSync(sourceDir).isDirectory()) { throw new Error('sourceDir is not a directory'); } // Create the tool dir const destPath = yield _createToolPath(tool, version, arch); // copy each child item. do not move. move can fail on Windows // due to anti-virus software having an open handle on a file. for (const itemName of fs.readdirSync(sourceDir)) { const s = path.join(sourceDir, itemName); yield io.cp(s, destPath, { recursive: true }); } // write .complete _completeToolPath(tool, version, arch); return destPath; }); } exports.cacheDir = cacheDir; /** * Caches a downloaded file (GUID) and installs it * into the tool cache with a given targetName * * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. * @param targetFile the name of the file name in the tools directory * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source file: ${sourceFile}`); if (!fs.statSync(sourceFile).isFile()) { throw new Error('sourceFile is not a file'); } // create the tool dir const destFolder = yield _createToolPath(tool, version, arch); // copy instead of move. move can fail on Windows due to // anti-virus software having an open handle on a file. const destPath = path.join(destFolder, targetFile); core.debug(`destination file ${destPath}`); yield io.cp(sourceFile, destPath); // write .complete _completeToolPath(tool, version, arch); return destFolder; }); } exports.cacheFile = cacheFile; /** * Finds the path to a tool version in the local installed tool cache * * @param toolName name of the tool * @param versionSpec version of the tool * @param arch optional arch. defaults to arch of computer */ function find(toolName, versionSpec, arch) { if (!toolName) { throw new Error('toolName parameter is required'); } if (!versionSpec) { throw new Error('versionSpec parameter is required'); } arch = arch || os.arch(); // attempt to resolve an explicit version if (!_isExplicitVersion(versionSpec)) { const localVersions = findAllVersions(toolName, arch); const match = _evaluateVersions(localVersions, versionSpec); versionSpec = match; } // check for the explicit version in the cache let toolPath = ''; if (versionSpec) { versionSpec = semver.clean(versionSpec) || ''; const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); core.debug(`checking cache: ${cachePath}`); if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); toolPath = cachePath; } else { core.debug('not found'); } } return toolPath; } exports.find = find; /** * Finds the paths to all versions of a tool that are installed in the local tool cache * * @param toolName name of the tool * @param arch optional arch. defaults to arch of computer */ function findAllVersions(toolName, arch) { const versions = []; arch = arch || os.arch(); const toolPath = path.join(_getCacheDirectory(), toolName); if (fs.existsSync(toolPath)) { const children = fs.readdirSync(toolPath); for (const child of children) { if (_isExplicitVersion(child)) { const fullPath = path.join(toolPath, child, arch || ''); if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { versions.push(child); } } } } return versions; } exports.findAllVersions = findAllVersions; function _createExtractFolder(dest) { return __awaiter(this, void 0, void 0, function* () { if (!dest) { // create a temp dir dest = path.join(_getTempDirectory(), v4_1.default()); } yield io.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); core.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io.rmRF(folderPath); yield io.rmRF(markerPath); yield io.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch) { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); const markerPath = `${folderPath}.complete`; fs.writeFileSync(markerPath, ''); core.debug('finished caching tool'); } function _isExplicitVersion(versionSpec) { const c = semver.clean(versionSpec) || ''; core.debug(`isExplicit: ${c}`); const valid = semver.valid(c) != null; core.debug(`explicit? ${valid}`); return valid; } function _evaluateVersions(versions, versionSpec) { let version = ''; core.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { if (semver.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; const satisfied = semver.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { core.debug(`matched: ${version}`); } else { core.debug('match not found'); } return version; } /** * Gets RUNNER_TOOL_CACHE */ function _getCacheDirectory() { const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); return cacheDirectory; } /** * Gets RUNNER_TEMP */ function _getTempDirectory() { const tempDirectory = process.env['RUNNER_TEMP'] || ''; assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); return tempDirectory; } /** * Gets a global variable */ function _getGlobal(key, defaultValue) { /* eslint-disable @typescript-eslint/no-explicit-any */ const value = global[key]; /* eslint-enable @typescript-eslint/no-explicit-any */ return value !== undefined ? value : defaultValue; } //# sourceMappingURL=tool-cache.js.map /***/ }), /***/ 539: /***/ (function(__unusedmodule, exports, __nested_webpack_require_236540__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_236540__(835); const http = __nested_webpack_require_236540__(605); const https = __nested_webpack_require_236540__(211); const pm = __nested_webpack_require_236540__(950); let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise(async (resolve, reject) => { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ async getJson(requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ async request(verb, requestUrl, data, headers) { if (this._disposed) { throw new Error('Client has already been disposed.'); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { await response.readBody(); await this._performExponentialBackoff(numTries); } } return response; } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { let parsedUrl = url.parse(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; let proxyUrl = pm.getProxyUrl(parsedUrl); let useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __nested_webpack_require_236540__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } static dateTimeDeserializer(key, value) { if (typeof value === 'string') { let a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } async _processResponse(res, options) { return new Promise(async (resolve, reject) => { const statusCode = res.message.statusCode; const response = { statusCode: statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response); } let obj; let contents; // get the result from the body try { contents = await res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = 'Failed request: (' + statusCode + ')'; } let err = new Error(msg); // attach statusCode and body obj (if available) to the error object err['statusCode'] = statusCode; if (response.result) { err['result'] = response.result; } reject(err); } else { resolve(response); } }); } } exports.HttpClient = HttpClient; /***/ }), /***/ 569: /***/ (function(module, __unusedexports, __nested_webpack_require_259230__) { module.exports = rimraf rimraf.sync = rimrafSync var assert = __nested_webpack_require_259230__(357) var path = __nested_webpack_require_259230__(622) var fs = __nested_webpack_require_259230__(747) var glob = undefined try { glob = __nested_webpack_require_259230__(402) } catch (_err) { // treat glob as optional. } var _0666 = parseInt('666', 8) var defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling var timeout = 0 var isWindows = (process.platform === "win32") function defaults (options) { var methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(function(m) { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } function rimraf (p, options, cb) { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) var busyTries = 0 var errState = null var n = 0 if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, function (er, stat) { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) function next (er) { errState = errState || er if (--n === 0) cb(errState) } function afterGlob (er, results) { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(function (p) { rimraf_(p, options, function CB (er) { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ var time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(function () { rimraf_(p, options, CB) }, time) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(function () { rimraf_(p, options, CB) }, timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) }) }) } } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, function (er, st) { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, function (er) { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') if (er) assert(er instanceof Error) options.chmod(p, _0666, function (er2) { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, function(er3, stats) { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } function fixWinEPERMSync (p, options, er) { assert(p) assert(options) if (er) assert(er instanceof Error) try { options.chmodSync(p, _0666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } try { var stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, function (er) { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } function rmkids(p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, function (er, files) { if (er) return cb(er) var n = files.length if (n === 0) return options.rmdir(p, cb) var errState files.forEach(function (f) { rimraf(path.join(p, f), options, function (er) { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') var results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (var i = 0; i < results.length; i++) { var p = results[i] try { var st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(function (f) { rimrafSync(path.join(p, f), options) }) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. var retries = isWindows ? 100 : 1 var i = 0 do { var threw = true try { var ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } /***/ }), /***/ 581: /***/ (function(module) { "use strict"; var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, merge: merge }; /***/ }), /***/ 605: /***/ (function(module) { module.exports = __webpack_require__(605); /***/ }), /***/ 614: /***/ (function(module) { module.exports = __webpack_require__(614); /***/ }), /***/ 621: /***/ (function(module) { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 622: /***/ (function(module) { module.exports = __webpack_require__(622); /***/ }), /***/ 631: /***/ (function(module) { module.exports = __webpack_require__(631); /***/ }), /***/ 669: /***/ (function(module) { module.exports = __webpack_require__(669); /***/ }), /***/ 672: /***/ (function(__unusedmodule, exports, __nested_webpack_require_276648__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); const assert_1 = __nested_webpack_require_276648__(357); const fs = __nested_webpack_require_276648__(747); const path = __nested_webpack_require_276648__(622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Recursively create a directory at `fsPath`. * * This implementation is optimistic, meaning it attempts to create the full * path first, and backs up the path stack from there. * * @param fsPath The path to create * @param maxDepth The maximum recursion depth * @param depth The current recursion depth */ function mkdirP(fsPath, maxDepth = 1000, depth = 1) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); fsPath = path.resolve(fsPath); if (depth >= maxDepth) return exports.mkdir(fsPath); try { yield exports.mkdir(fsPath); return; } catch (err) { switch (err.code) { case 'ENOENT': { yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); yield exports.mkdir(fsPath); return; } default: { let stats; try { stats = yield exports.stat(fsPath); } catch (err2) { throw err; } if (!stats.isDirectory()) throw err; } } } }); } exports.mkdirP = mkdirP; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } //# sourceMappingURL=io-util.js.map /***/ }), /***/ 674: /***/ (function(module, __unusedexports, __nested_webpack_require_284325__) { var wrappy = __nested_webpack_require_284325__(11) var reqs = Object.create(null) var once = __nested_webpack_require_284325__(49) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 681: /***/ (function(module) { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 689: /***/ (function(module, __unusedexports, __nested_webpack_require_286456__) { try { var util = __nested_webpack_require_286456__(669); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nested_webpack_require_286456__(315); } /***/ }), /***/ 722: /***/ (function(module) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 729: /***/ (function(__unusedmodule, exports, __nested_webpack_require_287622__) { "use strict"; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const qs = __nested_webpack_require_287622__(386); const url = __nested_webpack_require_287622__(835); const path = __nested_webpack_require_287622__(622); const zlib = __nested_webpack_require_287622__(761); /** * creates an url from a request url and optional base url (http://server:8080) * @param {string} resource - a fully qualified url or relative path * @param {string} baseUrl - an optional baseUrl (http://server:8080) * @param {IRequestOptions} options - an optional options object, could include QueryParameters e.g. * @return {string} - resultant url */ function getUrl(resource, baseUrl, queryParams) { const pathApi = path.posix || path; let requestUrl = ''; if (!baseUrl) { requestUrl = resource; } else if (!resource) { requestUrl = baseUrl; } else { const base = url.parse(baseUrl); const resultantUrl = url.parse(resource); // resource (specific per request) elements take priority resultantUrl.protocol = resultantUrl.protocol || base.protocol; resultantUrl.auth = resultantUrl.auth || base.auth; resultantUrl.host = resultantUrl.host || base.host; resultantUrl.pathname = pathApi.resolve(base.pathname, resultantUrl.pathname); if (!resultantUrl.pathname.endsWith('/') && resource.endsWith('/')) { resultantUrl.pathname += '/'; } requestUrl = url.format(resultantUrl); } return queryParams ? getUrlWithParsedQueryParams(requestUrl, queryParams) : requestUrl; } exports.getUrl = getUrl; /** * * @param {string} requestUrl * @param {IRequestQueryParams} queryParams * @return {string} - Request's URL with Query Parameters appended/parsed. */ function getUrlWithParsedQueryParams(requestUrl, queryParams) { const url = requestUrl.replace(/\?$/g, ''); // Clean any extra end-of-string "?" character const parsedQueryParams = qs.stringify(queryParams.params, buildParamsStringifyOptions(queryParams)); return `${url}${parsedQueryParams}`; } /** * Build options for QueryParams Stringifying. * * @param {IRequestQueryParams} queryParams * @return {object} */ function buildParamsStringifyOptions(queryParams) { let options = { addQueryPrefix: true, delimiter: (queryParams.options || {}).separator || '&', allowDots: (queryParams.options || {}).shouldAllowDots || false, arrayFormat: (queryParams.options || {}).arrayFormat || 'repeat', encodeValuesOnly: (queryParams.options || {}).shouldOnlyEncodeValues || true }; return options; } /** * Decompress/Decode gzip encoded JSON * Using Node.js built-in zlib module * * @param {Buffer} buffer * @param {string} charset? - optional; defaults to 'utf-8' * @return {Promise<string>} */ function decompressGzippedContent(buffer, charset) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { zlib.gunzip(buffer, function (error, buffer) { if (error) { reject(error); } resolve(buffer.toString(charset || 'utf-8')); }); })); }); } exports.decompressGzippedContent = decompressGzippedContent; /** * Obtain Response's Content Charset. * Through inspecting `content-type` response header. * It Returns 'utf-8' if NO charset specified/matched. * * @param {IHttpClientResponse} response * @return {string} - Content Encoding Charset; Default=utf-8 */ function obtainContentCharset(response) { // Find the charset, if specified. // Search for the `charset=CHARSET` string, not including `;,\r\n` // Example: content-type: 'application/json;charset=utf-8' // |__ matches would be ['charset=utf-8', 'utf-8', index: 18, input: 'application/json; charset=utf-8'] // |_____ matches[1] would have the charset :tada: , in our example it's utf-8 // However, if the matches Array was empty or no charset found, 'utf-8' would be returned by default. const nodeSupportedEncodings = ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'binary', 'hex']; const contentType = response.message.headers['content-type'] || ''; const matches = contentType.match(/charset=([^;,\r\n]+)/i); return (matches && matches[1] && nodeSupportedEncodings.indexOf(matches[1]) != -1) ? matches[1] : 'utf-8'; } exports.obtainContentCharset = obtainContentCharset; /***/ }), /***/ 747: /***/ (function(module) { module.exports = __webpack_require__(747); /***/ }), /***/ 755: /***/ (function(module, __unusedexports, __nested_webpack_require_293163__) { "use strict"; var utils = __nested_webpack_require_293163__(581); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = maybeMap( parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; // eslint-disable-line no-param-reassign } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }), /***/ 761: /***/ (function(module) { module.exports = __webpack_require__(761); /***/ }), /***/ 794: /***/ (function(module) { module.exports = __webpack_require__(794); /***/ }), /***/ 826: /***/ (function(module, __unusedexports, __nested_webpack_require_302857__) { var rng = __nested_webpack_require_302857__(139); var bytesToUuid = __nested_webpack_require_302857__(722); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 835: /***/ (function(module) { module.exports = __webpack_require__(835); /***/ }), /***/ 856: /***/ (function(__unusedmodule, exports, __nested_webpack_require_303709__) { exports.alphasort = alphasort exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var path = __nested_webpack_require_303709__(622) var minimatch = __nested_webpack_require_303709__(93) var isAbsolute = __nested_webpack_require_303709__(681) var Minimatch = minimatch.Minimatch function alphasorti (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 874: /***/ (function(__unusedmodule, exports, __nested_webpack_require_309974__) { "use strict"; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_309974__(835); const http = __nested_webpack_require_309974__(605); const https = __nested_webpack_require_309974__(211); const util = __nested_webpack_require_309974__(729); let fs; let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect]; const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { let buffer = Buffer.alloc(0); const encodingCharset = util.obtainContentCharset(this); // Extract Encoding from header: 'content-encoding' // Match `gzip`, `gzip, deflate` variations of GZIP encoding const contentEncoding = this.message.headers['content-encoding'] || ''; const isGzippedEncoded = new RegExp('(gzip$)|(gzip, *deflate)').test(contentEncoding); this.message.on('data', function (data) { const chunk = (typeof data === 'string') ? Buffer.from(data, encodingCharset) : data; buffer = Buffer.concat([buffer, chunk]); }).on('end', function () { return __awaiter(this, void 0, void 0, function* () { if (isGzippedEncoded) { // Process GZipped Response Body HERE const gunzippedBody = yield util.decompressGzippedContent(buffer, encodingCharset); resolve(gunzippedBody); } else { resolve(buffer.toString(encodingCharset)); } }); }).on('error', function (err) { reject(err); }); })); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; var EnvironmentVariables; (function (EnvironmentVariables) { EnvironmentVariables["HTTP_PROXY"] = "HTTP_PROXY"; EnvironmentVariables["HTTPS_PROXY"] = "HTTPS_PROXY"; EnvironmentVariables["NO_PROXY"] = "NO_PROXY"; })(EnvironmentVariables || (EnvironmentVariables = {})); class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; let no_proxy = process.env[EnvironmentVariables.NO_PROXY]; if (no_proxy) { this._httpProxyBypassHosts = []; no_proxy.split(',').forEach(bypass => { this._httpProxyBypassHosts.push(new RegExp(bypass, 'i')); }); } this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; this._httpProxy = requestOptions.proxy; if (requestOptions.proxy && requestOptions.proxy.proxyBypassHosts) { this._httpProxyBypassHosts = []; requestOptions.proxy.proxyBypassHosts.forEach(bypass => { this._httpProxyBypassHosts.push(new RegExp(bypass, 'i')); }); } this._certConfig = requestOptions.cert; if (this._certConfig) { // If using cert, need fs fs = __nested_webpack_require_309974__(747); // cache the cert content into memory, so we don't have to read it from disk every time if (this._certConfig.caFile && fs.existsSync(this._certConfig.caFile)) { this._ca = fs.readFileSync(this._certConfig.caFile, 'utf8'); } if (this._certConfig.certFile && fs.existsSync(this._certConfig.certFile)) { this._cert = fs.readFileSync(this._certConfig.certFile, 'utf8'); } if (this._certConfig.keyFile && fs.existsSync(this._certConfig.keyFile)) { this._key = fs.readFileSync(this._certConfig.keyFile, 'utf8'); } } if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error("Client has already been disposed."); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers["location"]; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof (data) === 'string') { info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', (sock) => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.destroy(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof (data) === 'string') { req.write(data, 'utf8'); } if (data && typeof (data) !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers["user-agent"] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers && !this._isPresigned(url.format(requestUrl))) { this.handlers.forEach((handler) => { handler.prepareRequest(info.options); }); } return info; } _isPresigned(requestUrl) { if (this.requestOptions && this.requestOptions.presignedUrlPatterns) { const patterns = this.requestOptions.presignedUrlPatterns; for (let i = 0; i < patterns.length; i++) { if (requestUrl.match(patterns[i])) { return true; } } } return false; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getAgent(parsedUrl) { let agent; let proxy = this._getProxy(parsedUrl); let useProxy = proxy.proxyUrl && proxy.proxyUrl.hostname && !this._isMatchInBypassProxyList(parsedUrl); if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __nested_webpack_require_309974__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxy.proxyAuth, host: proxy.proxyUrl.hostname, port: proxy.proxyUrl.port }, }; let tunnelAgent; const overHttps = proxy.proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } if (usingSsl && this._certConfig) { agent.options = Object.assign(agent.options || {}, { ca: this._ca, cert: this._cert, key: this._key, passphrase: this._certConfig.passphrase }); } return agent; } _getProxy(parsedUrl) { let usingSsl = parsedUrl.protocol === 'https:'; let proxyConfig = this._httpProxy; // fallback to http_proxy and https_proxy env let https_proxy = process.env[EnvironmentVariables.HTTPS_PROXY]; let http_proxy = process.env[EnvironmentVariables.HTTP_PROXY]; if (!proxyConfig) { if (https_proxy && usingSsl) { proxyConfig = { proxyUrl: https_proxy }; } else if (http_proxy) { proxyConfig = { proxyUrl: http_proxy }; } } let proxyUrl; let proxyAuth; if (proxyConfig) { if (proxyConfig.proxyUrl.length > 0) { proxyUrl = url.parse(proxyConfig.proxyUrl); } if (proxyConfig.proxyUsername || proxyConfig.proxyPassword) { proxyAuth = proxyConfig.proxyUsername + ":" + proxyConfig.proxyPassword; } } return { proxyUrl: proxyUrl, proxyAuth: proxyAuth }; } _isMatchInBypassProxyList(parsedUrl) { if (!this._httpProxyBypassHosts) { return false; } let bypass = false; this._httpProxyBypassHosts.forEach(bypassHost => { if (bypassHost.test(parsedUrl.href)) { bypass = true; } }); return bypass; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } } exports.HttpClient = HttpClient; /***/ }), /***/ 896: /***/ (function(module) { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 897: /***/ (function(module, __unusedexports, __nested_webpack_require_332817__) { "use strict"; var utils = __nested_webpack_require_332817__(581); var formats = __nested_webpack_require_332817__(13); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var stringify = function stringify( object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = obj.join(','); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key'); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (isArray(obj)) { pushToArray(values, stringify( obj[key], typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } else { pushToArray(values, stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.formatter, options.encodeValuesOnly, options.charset )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; /***/ }), /***/ 950: /***/ (function(__unusedmodule, exports, __nested_webpack_require_341202__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_341202__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; if (checkBypass(reqUrl)) { return proxyUrl; } let proxyVar; if (usingSsl) { proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = url.parse(proxyVar); } return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port let upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (let upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; /***/ }), /***/ 962: /***/ (function(__unusedmodule, exports, __nested_webpack_require_342935__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * Contains installation utility functions. */ const toolCache = __importStar(__nested_webpack_require_342935__(533)); const core = __importStar(__nested_webpack_require_342935__(470)); const path_1 = __importDefault(__nested_webpack_require_342935__(622)); exports.GCLOUD_METRICS_ENV_VAR = 'CLOUDSDK_METRICS_ENVIRONMENT'; exports.GCLOUD_METRICS_LABEL = 'github-actions-setup-gcloud'; /** * Installs the gcloud SDK into the actions environment. * * @param version The version being installed. * @param gcloudExtPath The extraction path for the gcloud SDK. * @returns The path of the installed tool. */ function installGcloudSDK(version, gcloudExtPath) { return __awaiter(this, void 0, void 0, function* () { const toolRoot = path_1.default.join(gcloudExtPath, 'google-cloud-sdk'); let toolPath = yield toolCache.cacheDir(toolRoot, 'gcloud', version); toolPath = path_1.default.join(toolPath, 'bin'); core.addPath(toolPath); core.exportVariable(exports.GCLOUD_METRICS_ENV_VAR, exports.GCLOUD_METRICS_LABEL); return toolPath; }); } exports.installGcloudSDK = installGcloudSDK; /***/ }), /***/ 979: /***/ (function(__unusedmodule, exports, __nested_webpack_require_345898__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__nested_webpack_require_345898__(470)); /** * Internal class for retries */ class RetryHelper { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { throw new Error('max attempts should be greater than or equal to 1'); } this.maxAttempts = maxAttempts; this.minSeconds = Math.floor(minSeconds); this.maxSeconds = Math.floor(maxSeconds); if (this.minSeconds > this.maxSeconds) { throw new Error('min seconds should be less than or equal to max seconds'); } } execute(action, isRetryable) { return __awaiter(this, void 0, void 0, function* () { let attempt = 1; while (attempt < this.maxAttempts) { // Try try { return yield action(); } catch (err) { if (isRetryable && !isRetryable(err)) { throw err; } core.info(err.message); } // Sleep const seconds = this.getSleepAmount(); core.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } // Last attempt return yield action(); }); } getSleepAmount() { return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds); } sleep(seconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, seconds * 1000)); }); } } exports.RetryHelper = RetryHelper; //# sourceMappingURL=retry-helper.js.map /***/ }), /***/ 986: /***/ (function(__unusedmodule, exports, __nested_webpack_require_348825__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const tr = __importStar(__nested_webpack_require_348825__(9)); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise<number> exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; //# sourceMappingURL=exec.js.map /***/ }) /******/ }); /***/ }), /***/ 722: /***/ (function(module) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 738: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const core = __importStar(__webpack_require__(470)); const toolCache = __importStar(__webpack_require__(533)); const setupGcloud = __importStar(__webpack_require__(702)); const fs_1 = __webpack_require__(747); const path_1 = __importDefault(__webpack_require__(622)); const uuid_1 = __webpack_require__(898); function run() { return __awaiter(this, void 0, void 0, function* () { try { let version = core.getInput('version'); if (!version || version == 'latest') { version = yield setupGcloud.getLatestGcloudSDKVersion(); } // Install the gcloud if not already present if (!setupGcloud.isInstalled()) { yield setupGcloud.installGcloudSDK(version); } else { const toolPath = toolCache.find('gcloud', version); core.addPath(path_1.default.join(toolPath, 'bin')); } // Set the project ID, if given. const projectId = core.getInput('project_id'); if (projectId) { yield setupGcloud.setProject(projectId); core.info('Successfully set default project'); } const serviceAccountKey = core.getInput('service_account_key'); // If a service account key isn't provided, log an un-authenticated notice if (!serviceAccountKey) { core.info('No credentials provided, skipping authentication'); return; } else { yield setupGcloud.authenticateGcloudSDK(serviceAccountKey); } // Export credentials if requested - these credentials must be exported in // the shared workspace directory, since the filesystem must be shared among // all steps. const exportCreds = core.getInput('export_default_credentials'); if (String(exportCreds).toLowerCase() === 'true') { const workspace = process.env.GITHUB_WORKSPACE; if (!workspace) { throw new Error('Missing GITHUB_WORKSPACE!'); } const credsPath = path_1.default.join(workspace, uuid_1.v4()); const serviceAccountKeyObj = setupGcloud.parseServiceAccountKey(serviceAccountKey); yield fs_1.promises.writeFile(credsPath, JSON.stringify(serviceAccountKeyObj, null, 2)); core.exportVariable('GCLOUD_PROJECT', projectId ? projectId : serviceAccountKeyObj.project_id); // If projectId is set export it, else export projectId from SA core.exportVariable('GOOGLE_APPLICATION_CREDENTIALS', credsPath); core.info('Successfully exported Default Application Credentials'); } } catch (error) { core.setFailed(error.message); } }); } run(); /***/ }), /***/ 747: /***/ (function(module) { module.exports = require("fs"); /***/ }), /***/ 761: /***/ (function(module) { module.exports = require("zlib"); /***/ }), /***/ 794: /***/ (function(module) { module.exports = require("stream"); /***/ }), /***/ 826: /***/ (function(module, __unusedexports, __webpack_require__) { var rng = __webpack_require__(139); var bytesToUuid = __webpack_require__(722); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 835: /***/ (function(module) { module.exports = require("url"); /***/ }), /***/ 898: /***/ (function(module, __unusedexports, __webpack_require__) { var v1 = __webpack_require__(86); var v4 = __webpack_require__(826); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; /***/ }), /***/ 950: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; if (checkBypass(reqUrl)) { return proxyUrl; } let proxyVar; if (usingSsl) { proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = url.parse(proxyVar); } return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port let upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (let upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; /***/ }), /***/ 979: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); /** * Internal class for retries */ class RetryHelper { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { throw new Error('max attempts should be greater than or equal to 1'); } this.maxAttempts = maxAttempts; this.minSeconds = Math.floor(minSeconds); this.maxSeconds = Math.floor(maxSeconds); if (this.minSeconds > this.maxSeconds) { throw new Error('min seconds should be less than or equal to max seconds'); } } execute(action, isRetryable) { return __awaiter(this, void 0, void 0, function* () { let attempt = 1; while (attempt < this.maxAttempts) { // Try try { return yield action(); } catch (err) { if (isRetryable && !isRetryable(err)) { throw err; } core.info(err.message); } // Sleep const seconds = this.getSleepAmount(); core.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } // Last attempt return yield action(); }); } getSleepAmount() { return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds); } sleep(seconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, seconds * 1000)); }); } } exports.RetryHelper = RetryHelper; //# sourceMappingURL=retry-helper.js.map /***/ }), /***/ 986: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const tr = __webpack_require__(9); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise<number> exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; //# sourceMappingURL=exec.js.map /***/ }) /******/ });
setup-gcloud/dist/index.js
module.exports = /******/ (function(modules, runtime) { // webpackBootstrap /******/ "use strict"; /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ __webpack_require__.ab = __dirname + "/"; /******/ /******/ // the startup function /******/ function startup() { /******/ // Load entry module and return exports /******/ return __webpack_require__(738); /******/ }; /******/ /******/ // run startup /******/ return startup(); /******/ }) /************************************************************************/ /******/ ({ /***/ 1: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const childProcess = __webpack_require__(129); const path = __webpack_require__(622); const util_1 = __webpack_require__(669); const ioUtil = __webpack_require__(672); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. try { if (yield ioUtil.isDirectory(inputPath, true)) { yield exec(`rd /s /q "${inputPath}"`); } else { yield exec(`del /f /a "${inputPath}"`); } } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } // Shelling out fails to remove a symlink folder with missing source, this unlink catches that try { yield ioUtil.unlink(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } } else { let isDir = false; try { isDir = yield ioUtil.isDirectory(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; return; } if (isDir) { yield exec(`rm -rf "${inputPath}"`); } else { yield ioUtil.unlink(inputPath); } } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise<void> */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { yield ioUtil.mkdirP(fsPath); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise<string> path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } } try { // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { for (const extension of process.env.PATHEXT.split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return filePath; } return ''; } // if any path separators, return empty if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { return ''; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // return the first match for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); if (filePath) { return filePath; } } return ''; } catch (err) { throw new Error(`which failed with message ${err.message}`); } }); } exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); return { force, recursive }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 9: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __webpack_require__(87); const events = __webpack_require__(614); const child = __webpack_require__(129); const path = __webpack_require__(622); const io = __webpack_require__(1); const ioUtil = __webpack_require__(672); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); }); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 16: /***/ (function(module) { module.exports = require("tls"); /***/ }), /***/ 86: /***/ (function(module, __unusedexports, __webpack_require__) { var rng = __webpack_require__(139); var bytesToUuid = __webpack_require__(722); // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [ seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] ]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); } module.exports = v1; /***/ }), /***/ 87: /***/ (function(module) { module.exports = require("os"); /***/ }), /***/ 129: /***/ (function(module) { module.exports = require("child_process"); /***/ }), /***/ 139: /***/ (function(module, __unusedexports, __webpack_require__) { // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = __webpack_require__(417); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; /***/ }), /***/ 141: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var net = __webpack_require__(631); var tls = __webpack_require__(16); var http = __webpack_require__(605); var https = __webpack_require__(211); var events = __webpack_require__(614); var assert = __webpack_require__(357); var util = __webpack_require__(669); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 211: /***/ (function(module) { module.exports = require("https"); /***/ }), /***/ 357: /***/ (function(module) { module.exports = require("assert"); /***/ }), /***/ 413: /***/ (function(module, __unusedexports, __webpack_require__) { module.exports = __webpack_require__(141); /***/ }), /***/ 417: /***/ (function(module) { module.exports = require("crypto"); /***/ }), /***/ 431: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__webpack_require__(87)); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return (s || '') .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return (s || '') .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 470: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const command_1 = __webpack_require__(431); const os = __importStar(__webpack_require__(87)); const path = __importStar(__webpack_require__(622)); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable */ function exportVariable(name, val) { process.env[name] = val; command_1.issueCommand('set-env', { name }, val); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { command_1.issueCommand('add-path', {}, inputPath); process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } return val.trim(); } exports.getInput = getInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store */ function setOutput(name, value) { command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message */ function error(message) { command_1.issue('error', message); } exports.error = error; /** * Adds an warning issue * @param message warning issue message */ function warning(message) { command_1.issue('warning', message); } exports.warning = warning; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store */ function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; //# sourceMappingURL=core.js.map /***/ }), /***/ 533: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); const io = __importStar(__webpack_require__(1)); const fs = __importStar(__webpack_require__(747)); const os = __importStar(__webpack_require__(87)); const path = __importStar(__webpack_require__(622)); const httpm = __importStar(__webpack_require__(539)); const semver = __importStar(__webpack_require__(550)); const stream = __importStar(__webpack_require__(794)); const util = __importStar(__webpack_require__(669)); const v4_1 = __importDefault(__webpack_require__(826)); const exec_1 = __webpack_require__(986); const assert_1 = __webpack_require__(357); const retry_helper_1 = __webpack_require__(979); class HTTPError extends Error { constructor(httpStatusCode) { super(`Unexpected HTTP response: ${httpStatusCode}`); this.httpStatusCode = httpStatusCode; Object.setPrototypeOf(this, new.target.prototype); } } exports.HTTPError = HTTPError; const IS_WINDOWS = process.platform === 'win32'; const userAgent = 'actions/tool-cache'; /** * Download a tool from an url and stream it into a file * * @param url url of tool to download * @param dest path to download tool * @returns path to downloaded tool */ function downloadTool(url, dest) { return __awaiter(this, void 0, void 0, function* () { dest = dest || path.join(_getTempDirectory(), v4_1.default()); yield io.mkdirP(path.dirname(dest)); core.debug(`Downloading ${url}`); core.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { return yield downloadToolAttempt(url, dest || ''); }), (err) => { if (err instanceof HTTPError && err.httpStatusCode) { // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { return false; } } // Otherwise retry return true; }); }); } exports.downloadTool = downloadTool; function downloadToolAttempt(url, dest) { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } // Get the response headers const http = new httpm.HttpClient(userAgent, [], { allowRetries: false }); const response = yield http.get(url); if (response.message.statusCode !== 200) { const err = new HTTPError(response.message.statusCode); core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } // Download the response body const pipeline = util.promisify(stream.pipeline); const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); const readStream = responseMessageFactory(); let succeeded = false; try { yield pipeline(readStream, fs.createWriteStream(dest)); core.debug('download complete'); succeeded = true; return dest; } finally { // Error, delete dest before retry if (!succeeded) { core.debug('download failed'); try { yield io.rmRF(dest); } catch (err) { core.debug(`Failed to delete '${dest}'. ${err.message}`); } } } }); } /** * Extract a .7z file * * @param file path to the .7z file * @param dest destination directory. Optional. * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line * interface, it is smaller than the full command line interface, and it does support long paths. At the * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path * to 7zr.exe can be pass to this function. * @returns path to the destination directory */ function extract7z(file, dest, _7zPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); assert_1.ok(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); const originalCwd = process.cwd(); process.chdir(dest); if (_7zPath) { try { const args = [ 'x', '-bb1', '-bd', '-sccUTF-8', file ]; const options = { silent: true }; yield exec_1.exec(`"${_7zPath}"`, args, options); } finally { process.chdir(originalCwd); } } else { const escapedScript = path .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') .replace(/'/g, "''") .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; const options = { silent: true }; try { const powershellPath = yield io.which('powershell', true); yield exec_1.exec(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); } } return dest; }); } exports.extract7z = extract7z; /** * Extract a compressed tar archive * * @param file path to the tar * @param dest destination directory. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. * @returns path to the destination directory */ function extractTar(file, dest, flags = 'xz') { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } // Create dest dest = yield _createExtractFolder(dest); // Determine whether GNU tar core.debug('Checking tar --version'); let versionOutput = ''; yield exec_1.exec('tar --version', [], { ignoreReturnCode: true, silent: true, listeners: { stdout: (data) => (versionOutput += data.toString()), stderr: (data) => (versionOutput += data.toString()) } }); core.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); // Initialize args const args = [flags]; let destArg = dest; let fileArg = file; if (IS_WINDOWS && isGnuTar) { args.push('--force-local'); destArg = dest.replace(/\\/g, '/'); // Technically only the dest needs to have `/` but for aesthetic consistency // convert slashes in the file arg too. fileArg = file.replace(/\\/g, '/'); } if (isGnuTar) { // Suppress warnings when using GNU tar to extract archives created by BSD tar args.push('--warning=no-unknown-keyword'); } args.push('-C', destArg, '-f', fileArg); yield exec_1.exec(`tar`, args); return dest; }); } exports.extractTar = extractTar; /** * Extract a zip * * @param file path to the zip * @param dest destination directory. Optional. * @returns path to the destination directory */ function extractZip(file, dest) { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); if (IS_WINDOWS) { yield extractZipWin(file, dest); } else { yield extractZipNix(file, dest); } return dest; }); } exports.extractZip = extractZip; function extractZipWin(file, dest) { return __awaiter(this, void 0, void 0, function* () { // build the powershell command const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; // run powershell const powershellPath = yield io.which('powershell'); const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; yield exec_1.exec(`"${powershellPath}"`, args); }); } function extractZipNix(file, dest) { return __awaiter(this, void 0, void 0, function* () { const unzipPath = yield io.which('unzip'); yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest }); }); } /** * Caches a directory and installs it into the tool cacheDir * * @param sourceDir the directory to cache into tools * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheDir(sourceDir, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source dir: ${sourceDir}`); if (!fs.statSync(sourceDir).isDirectory()) { throw new Error('sourceDir is not a directory'); } // Create the tool dir const destPath = yield _createToolPath(tool, version, arch); // copy each child item. do not move. move can fail on Windows // due to anti-virus software having an open handle on a file. for (const itemName of fs.readdirSync(sourceDir)) { const s = path.join(sourceDir, itemName); yield io.cp(s, destPath, { recursive: true }); } // write .complete _completeToolPath(tool, version, arch); return destPath; }); } exports.cacheDir = cacheDir; /** * Caches a downloaded file (GUID) and installs it * into the tool cache with a given targetName * * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. * @param targetFile the name of the file name in the tools directory * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source file: ${sourceFile}`); if (!fs.statSync(sourceFile).isFile()) { throw new Error('sourceFile is not a file'); } // create the tool dir const destFolder = yield _createToolPath(tool, version, arch); // copy instead of move. move can fail on Windows due to // anti-virus software having an open handle on a file. const destPath = path.join(destFolder, targetFile); core.debug(`destination file ${destPath}`); yield io.cp(sourceFile, destPath); // write .complete _completeToolPath(tool, version, arch); return destFolder; }); } exports.cacheFile = cacheFile; /** * Finds the path to a tool version in the local installed tool cache * * @param toolName name of the tool * @param versionSpec version of the tool * @param arch optional arch. defaults to arch of computer */ function find(toolName, versionSpec, arch) { if (!toolName) { throw new Error('toolName parameter is required'); } if (!versionSpec) { throw new Error('versionSpec parameter is required'); } arch = arch || os.arch(); // attempt to resolve an explicit version if (!_isExplicitVersion(versionSpec)) { const localVersions = findAllVersions(toolName, arch); const match = _evaluateVersions(localVersions, versionSpec); versionSpec = match; } // check for the explicit version in the cache let toolPath = ''; if (versionSpec) { versionSpec = semver.clean(versionSpec) || ''; const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); core.debug(`checking cache: ${cachePath}`); if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); toolPath = cachePath; } else { core.debug('not found'); } } return toolPath; } exports.find = find; /** * Finds the paths to all versions of a tool that are installed in the local tool cache * * @param toolName name of the tool * @param arch optional arch. defaults to arch of computer */ function findAllVersions(toolName, arch) { const versions = []; arch = arch || os.arch(); const toolPath = path.join(_getCacheDirectory(), toolName); if (fs.existsSync(toolPath)) { const children = fs.readdirSync(toolPath); for (const child of children) { if (_isExplicitVersion(child)) { const fullPath = path.join(toolPath, child, arch || ''); if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { versions.push(child); } } } } return versions; } exports.findAllVersions = findAllVersions; function _createExtractFolder(dest) { return __awaiter(this, void 0, void 0, function* () { if (!dest) { // create a temp dir dest = path.join(_getTempDirectory(), v4_1.default()); } yield io.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); core.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io.rmRF(folderPath); yield io.rmRF(markerPath); yield io.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch) { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); const markerPath = `${folderPath}.complete`; fs.writeFileSync(markerPath, ''); core.debug('finished caching tool'); } function _isExplicitVersion(versionSpec) { const c = semver.clean(versionSpec) || ''; core.debug(`isExplicit: ${c}`); const valid = semver.valid(c) != null; core.debug(`explicit? ${valid}`); return valid; } function _evaluateVersions(versions, versionSpec) { let version = ''; core.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { if (semver.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; const satisfied = semver.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { core.debug(`matched: ${version}`); } else { core.debug('match not found'); } return version; } /** * Gets RUNNER_TOOL_CACHE */ function _getCacheDirectory() { const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); return cacheDirectory; } /** * Gets RUNNER_TEMP */ function _getTempDirectory() { const tempDirectory = process.env['RUNNER_TEMP'] || ''; assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); return tempDirectory; } /** * Gets a global variable */ function _getGlobal(key, defaultValue) { /* eslint-disable @typescript-eslint/no-explicit-any */ const value = global[key]; /* eslint-enable @typescript-eslint/no-explicit-any */ return value !== undefined ? value : defaultValue; } //# sourceMappingURL=tool-cache.js.map /***/ }), /***/ 539: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __webpack_require__(835); const http = __webpack_require__(605); const https = __webpack_require__(211); const pm = __webpack_require__(950); let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise(async (resolve, reject) => { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ async getJson(requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ async request(verb, requestUrl, data, headers) { if (this._disposed) { throw new Error('Client has already been disposed.'); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { await response.readBody(); await this._performExponentialBackoff(numTries); } } return response; } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { let parsedUrl = url.parse(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; let proxyUrl = pm.getProxyUrl(parsedUrl); let useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __webpack_require__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } static dateTimeDeserializer(key, value) { if (typeof value === 'string') { let a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } async _processResponse(res, options) { return new Promise(async (resolve, reject) => { const statusCode = res.message.statusCode; const response = { statusCode: statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response); } let obj; let contents; // get the result from the body try { contents = await res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = 'Failed request: (' + statusCode + ')'; } let err = new Error(msg); // attach statusCode and body obj (if available) to the error object err['statusCode'] = statusCode; if (response.result) { err['result'] = response.result; } reject(err); } else { resolve(response); } }); } } exports.HttpClient = HttpClient; /***/ }), /***/ 550: /***/ (function(module, exports) { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 605: /***/ (function(module) { module.exports = require("http"); /***/ }), /***/ 614: /***/ (function(module) { module.exports = require("events"); /***/ }), /***/ 622: /***/ (function(module) { module.exports = require("path"); /***/ }), /***/ 631: /***/ (function(module) { module.exports = require("net"); /***/ }), /***/ 669: /***/ (function(module) { module.exports = require("util"); /***/ }), /***/ 672: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); const assert_1 = __webpack_require__(357); const fs = __webpack_require__(747); const path = __webpack_require__(622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Recursively create a directory at `fsPath`. * * This implementation is optimistic, meaning it attempts to create the full * path first, and backs up the path stack from there. * * @param fsPath The path to create * @param maxDepth The maximum recursion depth * @param depth The current recursion depth */ function mkdirP(fsPath, maxDepth = 1000, depth = 1) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); fsPath = path.resolve(fsPath); if (depth >= maxDepth) return exports.mkdir(fsPath); try { yield exports.mkdir(fsPath); return; } catch (err) { switch (err.code) { case 'ENOENT': { yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); yield exports.mkdir(fsPath); return; } default: { let stats; try { stats = yield exports.stat(fsPath); } catch (err2) { throw err; } if (!stats.isDirectory()) throw err; } } } }); } exports.mkdirP = mkdirP; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } //# sourceMappingURL=io-util.js.map /***/ }), /***/ 702: /***/ (function(module, __unusedexports, __webpack_require__) { module.exports = /******/ (function(modules, runtime) { // webpackBootstrap /******/ "use strict"; /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ __webpack_require__.ab = __dirname + "/"; /******/ /******/ // the startup function /******/ function startup() { /******/ // Load entry module and return exports /******/ return __webpack_require__(325); /******/ }; /******/ /******/ // run startup /******/ return startup(); /******/ }) /************************************************************************/ /******/ ({ /***/ 1: /***/ (function(__unusedmodule, exports, __nested_webpack_require_1416__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const childProcess = __nested_webpack_require_1416__(129); const path = __nested_webpack_require_1416__(622); const util_1 = __nested_webpack_require_1416__(669); const ioUtil = __nested_webpack_require_1416__(672); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. try { if (yield ioUtil.isDirectory(inputPath, true)) { yield exec(`rd /s /q "${inputPath}"`); } else { yield exec(`del /f /a "${inputPath}"`); } } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } // Shelling out fails to remove a symlink folder with missing source, this unlink catches that try { yield ioUtil.unlink(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; } } else { let isDir = false; try { isDir = yield ioUtil.isDirectory(inputPath); } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code !== 'ENOENT') throw err; return; } if (isDir) { yield exec(`rm -rf "${inputPath}"`); } else { yield ioUtil.unlink(inputPath); } } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise<void> */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { yield ioUtil.mkdirP(fsPath); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise<string> path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } } try { // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { for (const extension of process.env.PATHEXT.split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return filePath; } return ''; } // if any path separators, return empty if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { return ''; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // return the first match for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); if (filePath) { return filePath; } } return ''; } catch (err) { throw new Error(`which failed with message ${err.message}`); } }); } exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); return { force, recursive }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 8: /***/ (function(__unusedmodule, exports, __nested_webpack_require_13050__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getReleaseURL = void 0; const httpm = __importStar(__nested_webpack_require_13050__(874)); const attempt_1 = __nested_webpack_require_13050__(503); const install_util_1 = __nested_webpack_require_13050__(962); /** * Formats the gcloud SDK release URL according to the specified arguments. * * @param os The OS of the requested release. * @param arch The system architecture of the requested release. * @param version The version of the requested release. * @returns The formatted gcloud SDK release URL. */ function formatReleaseURL(os, arch, version) { // massage the arch to match gcloud sdk conventions if (arch == 'x64') { arch = 'x86_64'; } let objectName; switch (os) { case 'linux': objectName = `google-cloud-sdk-${version}-linux-${arch}.tar.gz`; break; case 'darwin': objectName = `google-cloud-sdk-${version}-darwin-${arch}.tar.gz`; break; case 'win32': objectName = `google-cloud-sdk-${version}-windows-${arch}.zip`; break; default: throw new Error(`Unexpected OS '${os}'`); } return encodeURI(`https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/${objectName}`); } /** * Creates the gcloud SDK release URL for the specified arguments, verifying * its existence. * * @param os The OS of the requested release. * @param arch The system architecture of the requested release. * @param version The version of the requested release. * @returns The verified gcloud SDK release URL. */ function getReleaseURL(os, arch, version) { return __awaiter(this, void 0, void 0, function* () { try { const url = formatReleaseURL(os, arch, version); const client = new httpm.HttpClient(install_util_1.GCLOUD_METRICS_LABEL); return attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { const res = yield client.head(url); if (res.message.statusCode === 200) { return url; } else { throw new Error(`error code: ${res.message.statusCode}`); } }), { delay: 200, factor: 2, maxAttempts: 4, }); } catch (err) { throw new Error(`Error trying to get gcloud SDK release URL: os: ${os} arch: ${arch} version: ${version}, err: ${err}`); } }); } exports.getReleaseURL = getReleaseURL; /***/ }), /***/ 9: /***/ (function(__unusedmodule, exports, __nested_webpack_require_17825__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__nested_webpack_require_17825__(87)); const events = __importStar(__nested_webpack_require_17825__(614)); const child = __importStar(__nested_webpack_require_17825__(129)); const path = __importStar(__nested_webpack_require_17825__(622)); const io = __importStar(__nested_webpack_require_17825__(1)); const ioUtil = __importStar(__nested_webpack_require_17825__(672)); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } }); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 11: /***/ (function(module) { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 13: /***/ (function(module, __unusedexports, __nested_webpack_require_43219__) { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; var util = __nested_webpack_require_43219__(581); var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = util.assign( { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } } }, Format ); /***/ }), /***/ 16: /***/ (function(module) { module.exports = __webpack_require__(16); /***/ }), /***/ 31: /***/ (function(module, exports, __nested_webpack_require_43909__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const semver = __importStar(__nested_webpack_require_43909__(280)); const core_1 = __nested_webpack_require_43909__(470); // needs to be require for core node modules to be mocked /* eslint @typescript-eslint/no-require-imports: 0 */ const os = __nested_webpack_require_43909__(87); const cp = __nested_webpack_require_43909__(129); const fs = __nested_webpack_require_43909__(747); function _findMatch(versionSpec, stable, candidates, archFilter) { return __awaiter(this, void 0, void 0, function* () { const platFilter = os.platform(); let result; let match; let file; for (const candidate of candidates) { const version = candidate.version; core_1.debug(`check ${version} satisfies ${versionSpec}`); if (semver.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { file = candidate.files.find(item => { core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); let chk = item.arch === archFilter && item.platform === platFilter; if (chk && item.platform_version) { const osVersion = module.exports._getOsVersion(); if (osVersion === item.platform_version) { chk = true; } else { chk = semver.satisfies(osVersion, item.platform_version); } } return chk; }); if (file) { core_1.debug(`matched ${candidate.version}`); match = candidate; break; } } } if (match && file) { // clone since we're mutating the file list to be only the file that matches result = Object.assign({}, match); result.files = [file]; } return result; }); } exports._findMatch = _findMatch; function _getOsVersion() { // TODO: add windows and other linux, arm variants // right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python) const plat = os.platform(); let version = ''; if (plat === 'darwin') { version = cp.execSync('sw_vers -productVersion').toString(); } else if (plat === 'linux') { // lsb_release process not in some containers, readfile // Run cat /etc/lsb-release // DISTRIB_ID=Ubuntu // DISTRIB_RELEASE=18.04 // DISTRIB_CODENAME=bionic // DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS" const lsbContents = module.exports._readLinuxVersionFile(); if (lsbContents) { const lines = lsbContents.split('\n'); for (const line of lines) { const parts = line.split('='); if (parts.length === 2 && parts[0].trim() === 'DISTRIB_RELEASE') { version = parts[1].trim(); break; } } } } return version; } exports._getOsVersion = _getOsVersion; function _readLinuxVersionFile() { const lsbFile = '/etc/lsb-release'; let contents = ''; if (fs.existsSync(lsbFile)) { contents = fs.readFileSync(lsbFile).toString(); } return contents; } exports._readLinuxVersionFile = _readLinuxVersionFile; //# sourceMappingURL=manifest.js.map /***/ }), /***/ 49: /***/ (function(module, __unusedexports, __nested_webpack_require_48507__) { var wrappy = __nested_webpack_require_48507__(11) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 71: /***/ (function(__unusedmodule, exports, __nested_webpack_require_49536__) { "use strict"; /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getLatestGcloudSDKVersion = void 0; /** * Contains version utility functions. */ const httpm = __importStar(__nested_webpack_require_49536__(874)); const attempt_1 = __nested_webpack_require_49536__(503); const install_util_1 = __nested_webpack_require_49536__(962); /** * @returns The latest stable version of the gcloud SDK. */ function getLatestGcloudSDKVersion() { return __awaiter(this, void 0, void 0, function* () { const queryUrl = 'https://dl.google.com/dl/cloudsdk/channels/rapid/components-2.json'; const client = new httpm.HttpClient(install_util_1.GCLOUD_METRICS_LABEL); return yield attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { const res = yield client.get(queryUrl); if (res.message.statusCode != 200) { throw new Error(`Failed to retrieve gcloud SDK version, HTTP error code: ${res.message.statusCode} url: ${queryUrl}`); } const body = yield res.readBody(); const responseObject = JSON.parse(body); if (!responseObject.version) { throw new Error(`Failed to retrieve gcloud SDK version, invalid response body: ${body}`); } return responseObject.version; }), { delay: 200, factor: 2, maxAttempts: 4, }); }); } exports.getLatestGcloudSDKVersion = getLatestGcloudSDKVersion; /***/ }), /***/ 87: /***/ (function(module) { module.exports = __webpack_require__(87); /***/ }), /***/ 93: /***/ (function(module, __unusedexports, __nested_webpack_require_53285__) { module.exports = minimatch minimatch.Minimatch = Minimatch var path = { sep: '/' } try { path = __nested_webpack_require_53285__(622) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nested_webpack_require_53285__(306) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {} b = b || {} var t = {} Object.keys(b).forEach(function (k) { t[k] = b[k] }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = console.error this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { case '/': // completely not allowed, even escaped. // Should already be path-split by now. return false case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:<pattern>)<type> re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '.': case '[': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { hit = f === p } this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') return emptyFileEnd } // should be unreachable. throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 117: /***/ (function(__unusedmodule, exports, __nested_webpack_require_78728__) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __nested_webpack_require_78728__(622); var isWindows = process.platform === 'win32'; var fs = __nested_webpack_require_78728__(747); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 129: /***/ (function(module) { module.exports = __webpack_require__(129); /***/ }), /***/ 139: /***/ (function(module, __unusedexports, __nested_webpack_require_87472__) { // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = __nested_webpack_require_87472__(417); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; /***/ }), /***/ 141: /***/ (function(__unusedmodule, exports, __nested_webpack_require_87814__) { "use strict"; var net = __nested_webpack_require_87814__(631); var tls = __nested_webpack_require_87814__(16); var http = __nested_webpack_require_87814__(605); var https = __nested_webpack_require_87814__(211); var events = __nested_webpack_require_87814__(614); var assert = __nested_webpack_require_87814__(357); var util = __nested_webpack_require_87814__(669); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 150: /***/ (function(module, __unusedexports, __nested_webpack_require_95591__) { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan <[email protected]> * * MIT Licensed */ /* * Module dependencies. */ const fs = __nested_webpack_require_95591__(747); const os = __nested_webpack_require_95591__(87); const path = __nested_webpack_require_95591__(622); const crypto = __nested_webpack_require_95591__(417); const _c = fs.constants && os.constants ? { fs: fs.constants, os: os.constants } : process.binding('constants'); const rimraf = __nested_webpack_require_95591__(569); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448 /* 0o700 */, FILE_MODE = 384 /* 0o600 */, EXIT = 'exit', SIGINT = 'SIGINT', // this will hold the objects need to be removed on exit _removeObjects = []; var _gracefulCleanup = false; /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { var value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|Function)} options * @param {Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } return [options, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = _getTmpDir(); // fail early on missing tmp dir if (isBlank(opts.dir) && isBlank(tmpDir)) { throw new Error('No tmp dir specified'); } /* istanbul ignore else */ if (!isBlank(opts.name)) { return path.join(opts.dir || tmpDir, opts.name); } // mkstemps like template // opts.template has already been guarded in tmpName() below /* istanbul ignore else */ if (opts.template) { var template = opts.template; // make sure that we prepend the tmp path if none was given /* istanbul ignore else */ if (path.basename(template) === template) template = path.join(opts.dir || tmpDir, template); return template.replace(TEMPLATE_PATTERN, _randomChars(6)); } // prefix and postfix const name = [ (isBlank(opts.prefix) ? 'tmp-' : opts.prefix), process.pid, _randomChars(12), (opts.postfix ? opts.postfix : '') ].join(''); return path.join(opts.dir || tmpDir, name); } /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) return cb(new Error('Invalid tries')); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) return cb(new Error('Invalid template provided')); (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { var args = _parseArguments(options), opts = args[0], tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES; /* istanbul ignore else */ if (isNaN(tries) || tries < 0) throw new Error('Invalid tries'); /* istanbul ignore else */ if (opts.template && !opts.template.match(TEMPLATE_PATTERN)) throw new Error('Invalid template provided'); do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|fileCallback)} options the config options or the callback function * @param {?fileCallback} callback */ function file(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbul ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(err) { /* istanbul ignore else */ if (err) { // Low probability, and the file exists, so this could be // ignored. If it isn't we certainly need to unlink the // file, and if that fails too its error is more // important. try { fs.unlinkSync(name); } catch (e) { if (!isENOENT(e)) { err = e; } } return cb(err); } cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts)); }); } /* istanbul ignore else */ if (opts.detachDescriptor) { return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts)); } cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts)); }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { var args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { var args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { var args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); } if (0 <= fdPath[0]) fs.close(fdPath[0], function (err) { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!isEBADF(e) && !isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!isENOENT(e)) throw e; } } } /** * Prepares the callback for removal of the temporary file. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @returns {fileCallback} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Simple wrapper for rimraf. * * @param {string} dirPath * @param {Function} next * @private */ function _rimrafRemoveDirWrapper(dirPath, next) { rimraf(dirPath, next); } /** * Simple wrapper for rimraf.sync. * * @param {string} dirPath * @private */ function _rimrafRemoveDirSyncWrapper(dirPath, next) { try { return next(null, rimraf.sync(dirPath)); } catch (err) { return next(err); } } /** * Prepares the callback for removal of the temporary directory. * * @param {string} name * @param {Object} opts * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts) { const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs); const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name); const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * @param {Function} removeFunction * @param {Object} arg * @returns {Function} * @private */ function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) { var called = false; return function _cleanupCallback(next) { next = next || function () {}; if (!called) { const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; // sync? if (removeFunction.length === 1) { try { removeFunction(arg); return next(null); } catch (err) { // if no next is provided and since we are // in silent cleanup mode on process exit, // we will ignore the error return next(err); } } else return removeFunction(arg, next); } else return next(new Error('cleanup callback has already been called')); }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. */ function isEBADF(error) { return isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. */ function isENOENT(error) { return isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {string|number} any numerical value will be negated * * - Node >= 6.0 < 7.0: * error.code {string} * error.errno {number} negated * * - Node >= 4.0 < 6.0: introduces SystemError * error.code {string} * error.errno {number} negated * * - Node >= 0.10 < 4.0: * error.code {number} negated * error.errno n/a */ function isExpectedError(error, code, errno) { return error.code === code || error.code === errno; } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function isBlank(s) { return s === null || s === undefined || !s.trim(); } /** * Sets the graceful cleanup. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @returns {string} the currently configured tmp dir */ function _getTmpDir() { return os.tmpdir(); } /** * If there are multiple different versions of tmp in place, make sure that * we recognize the old listeners. * * @param {Function} listener * @private * @returns {Boolean} true whether listener is a legacy listener */ function _is_legacy_listener(listener) { return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown') && listener.toString().indexOf('_garbageCollector();') > -1; } /** * Safely install SIGINT listener. * * NOTE: this will only work on OSX and Linux. * * @private */ function _safely_install_sigint_listener() { const listeners = process.listeners(SIGINT); const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ if (lstnr.name === '_tmp$sigint_listener') { existingListeners.push(lstnr); process.removeListener(SIGINT, lstnr); } } process.on(SIGINT, function _tmp$sigint_listener(doExit) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](false); } catch (err) { // ignore } } try { // force the garbage collector even it is called again in the exit listener _garbageCollector(); } finally { if (!!doExit) { process.exit(0); } } }); } /** * Safely install process exit listener. * * @private */ function _safely_install_exit_listener() { const listeners = process.listeners(EXIT); // collect any existing listeners const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ // TODO: remove support for legacy listeners once release 1.0.0 is out if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) { // we must forget about the uncaughtException listener, hopefully it is ours if (lstnr.name !== '_uncaughtExceptionThrown') { existingListeners.push(lstnr); } process.removeListener(EXIT, lstnr); } } // TODO: what was the data parameter good for? process.addListener(EXIT, function _tmp$safe_listener(data) { for (let i = 0, length = existingListeners.length; i < length; i++) { // let the existing listener do the garbage collection (e.g. jest sandbox) try { existingListeners[i](data); } catch (err) { // ignore } } _garbageCollector(); }); } _safely_install_exit_listener(); _safely_install_sigint_listener(); /** * Configuration options. * * @typedef {Object} Options * @property {?number} tries the number of tries before give up the name generation * @property {?string} template the "mkstemp" like filename template * @property {?string} name fix name * @property {?string} dir the tmp directory to use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call after entry was removed */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, 'tmpdir', { enumerable: true, configurable: false, get: function () { return _getTmpDir(); } }); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 211: /***/ (function(module) { module.exports = __webpack_require__(211); /***/ }), /***/ 245: /***/ (function(module, __unusedexports, __nested_webpack_require_115426__) { module.exports = globSync globSync.GlobSync = GlobSync var fs = __nested_webpack_require_115426__(747) var rp = __nested_webpack_require_115426__(302) var minimatch = __nested_webpack_require_115426__(93) var Minimatch = minimatch.Minimatch var Glob = __nested_webpack_require_115426__(402).Glob var util = __nested_webpack_require_115426__(669) var path = __nested_webpack_require_115426__(622) var assert = __nested_webpack_require_115426__(357) var isAbsolute = __nested_webpack_require_115426__(681) var common = __nested_webpack_require_115426__(856) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 280: /***/ (function(module, exports) { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 302: /***/ (function(module, __unusedexports, __nested_webpack_require_169751__) { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nested_webpack_require_169751__(747) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nested_webpack_require_169751__(117) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 306: /***/ (function(module, __unusedexports, __nested_webpack_require_171164__) { var concatMap = __nested_webpack_require_171164__(896); var balanced = __nested_webpack_require_171164__(621); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 315: /***/ (function(module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 325: /***/ (function(__unusedmodule, exports, __nested_webpack_require_176851__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setProjectWithKey = exports.setProject = exports.authenticateGcloudSDK = exports.parseServiceAccountKey = exports.installGcloudSDK = exports.isAuthenticated = exports.isProjectIdSet = exports.getToolCommand = exports.isInstalled = exports.getLatestGcloudSDKVersion = void 0; const exec = __importStar(__nested_webpack_require_176851__(986)); const toolCache = __importStar(__nested_webpack_require_176851__(533)); const os = __importStar(__nested_webpack_require_176851__(87)); const tmp = __importStar(__nested_webpack_require_176851__(150)); const format_url_1 = __nested_webpack_require_176851__(8); const downloadUtil = __importStar(__nested_webpack_require_176851__(339)); const installUtil = __importStar(__nested_webpack_require_176851__(962)); const version_util_1 = __nested_webpack_require_176851__(71); Object.defineProperty(exports, "getLatestGcloudSDKVersion", { enumerable: true, get: function () { return version_util_1.getLatestGcloudSDKVersion; } }); /** * Checks if gcloud is installed. * * @param version (Optional) Cloud SDK version. * @return true if gcloud is found in toolpath. */ function isInstalled(version) { let toolPath; if (version) { toolPath = toolCache.find('gcloud', version); return toolPath != undefined && toolPath !== ''; } else { toolPath = toolCache.findAllVersions('gcloud'); return toolPath.length > 0; } } exports.isInstalled = isInstalled; /** * Returns the correct gcloud command for OS. * * @returns gcloud command. */ function getToolCommand() { // A workaround for https://github.com/actions/toolkit/issues/229 // Currently exec on windows runs as cmd shell. let toolCommand = 'gcloud'; if (process.platform == 'win32') { toolCommand = 'gcloud.cmd'; } return toolCommand; } exports.getToolCommand = getToolCommand; /** * Checks if the project Id is set in the gcloud config. * * @returns true is project Id is set. */ function isProjectIdSet() { return __awaiter(this, void 0, void 0, function* () { // stdout captures project id let output = ''; const stdout = (data) => { output += data.toString(); }; // stderr captures "(unset)" let errOutput = ''; const stderr = (data) => { errOutput += data.toString(); }; const options = { listeners: { stdout, stderr, }, }; const toolCommand = getToolCommand(); yield exec.exec(toolCommand, ['config', 'get-value', 'project'], options); return !(output.includes('unset') || errOutput.includes('unset')); }); } exports.isProjectIdSet = isProjectIdSet; /** * Checks if gcloud is authenticated. * * @returns true is gcloud is authenticated. */ function isAuthenticated() { return __awaiter(this, void 0, void 0, function* () { let output = ''; const stdout = (data) => { output += data.toString(); }; const options = { listeners: { stdout, }, }; const toolCommand = getToolCommand(); yield exec.exec(toolCommand, ['auth', 'list'], options); return !output.includes('No credentialed accounts.'); }); } exports.isAuthenticated = isAuthenticated; /** * Installs the gcloud SDK into the actions environment. * * @param version The version being installed. * @returns The path of the installed tool. */ function installGcloudSDK(version) { return __awaiter(this, void 0, void 0, function* () { // Retreive the release corresponding to the specified version and OS const osPlat = os.platform(); const osArch = os.arch(); const url = yield format_url_1.getReleaseURL(osPlat, osArch, version); // Download and extract the release const extPath = yield downloadUtil.downloadAndExtractTool(url); if (!extPath) { throw new Error(`Failed to download release, url: ${url}`); } // Install the downloaded release into the github action env return yield installUtil.installGcloudSDK(version, extPath); }); } exports.installGcloudSDK = installGcloudSDK; /** * Parses the service account string into JSON. * * @param serviceAccountKey The service account key used for authentication. * @returns ServiceAccountKey as an object. */ function parseServiceAccountKey(serviceAccountKey) { let serviceAccount = serviceAccountKey; // Handle base64-encoded credentials if (!serviceAccountKey.trim().startsWith('{')) { serviceAccount = Buffer.from(serviceAccountKey, 'base64').toString('utf8'); } return JSON.parse(serviceAccount); } exports.parseServiceAccountKey = parseServiceAccountKey; /** * Authenticates the gcloud tool using a service account key. * * @param serviceAccountKey The service account key used for authentication. * @returns exit code. */ function authenticateGcloudSDK(serviceAccountKey) { return __awaiter(this, void 0, void 0, function* () { tmp.setGracefulCleanup(); const serviceAccountJson = parseServiceAccountKey(serviceAccountKey); const serviceAccountEmail = serviceAccountJson.client_email; const toolCommand = getToolCommand(); // Authenticate as the specified service account. const options = { input: Buffer.from(JSON.stringify(serviceAccountJson)) }; return yield exec.exec(toolCommand, [ '--quiet', 'auth', 'activate-service-account', serviceAccountEmail, '--key-file', '-', ], options); }); } exports.authenticateGcloudSDK = authenticateGcloudSDK; /** * Sets the GCP Project Id in the gcloud config. * * @param serviceAccountKey The service account key used for authentication. * @returns project ID. */ function setProject(projectId) { return __awaiter(this, void 0, void 0, function* () { const toolCommand = getToolCommand(); return yield exec.exec(toolCommand, [ '--quiet', 'config', 'set', 'project', projectId, ]); }); } exports.setProject = setProject; /** * Sets the GCP Project Id in the gcloud config. * * @param serviceAccountKey The service account key used for authentication. * @returns project ID. */ function setProjectWithKey(serviceAccountKey) { return __awaiter(this, void 0, void 0, function* () { const serviceAccountJson = parseServiceAccountKey(serviceAccountKey); yield setProject(serviceAccountJson.project_id); return serviceAccountJson.project_id; }); } exports.setProjectWithKey = setProjectWithKey; /***/ }), /***/ 339: /***/ (function(__unusedmodule, exports, __nested_webpack_require_185781__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.downloadAndExtractTool = void 0; /** * Contains download utility functions. */ const toolCache = __importStar(__nested_webpack_require_185781__(533)); const attempt_1 = __nested_webpack_require_185781__(503); /** * Downloads and extracts the tool at the specified URL. * * @url The URL of the tool to be downloaded. * @returns The path to the locally extracted tool. */ function downloadAndExtractTool(url) { return __awaiter(this, void 0, void 0, function* () { const downloadPath = yield attempt_1.retry(() => __awaiter(this, void 0, void 0, function* () { return toolCache.downloadTool(url); }), { delay: 200, factor: 2, maxAttempts: 4, }); let extractedPath; if (url.indexOf('.zip') != -1) { extractedPath = yield toolCache.extractZip(downloadPath); } else if (url.indexOf('.tar.gz') != -1) { extractedPath = yield toolCache.extractTar(downloadPath); } else if (url.indexOf('.7z') != -1) { extractedPath = yield toolCache.extract7z(downloadPath); } else { throw new Error(`Unexpected download archive type, downloadPath: ${downloadPath}`); } return extractedPath; }); } exports.downloadAndExtractTool = downloadAndExtractTool; /***/ }), /***/ 357: /***/ (function(module) { module.exports = __webpack_require__(357); /***/ }), /***/ 386: /***/ (function(module, __unusedexports, __nested_webpack_require_189445__) { "use strict"; var stringify = __nested_webpack_require_189445__(897); var parse = __nested_webpack_require_189445__(755); var formats = __nested_webpack_require_189445__(13); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /***/ 402: /***/ (function(module, __unusedexports, __nested_webpack_require_189757__) { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var fs = __nested_webpack_require_189757__(747) var rp = __nested_webpack_require_189757__(302) var minimatch = __nested_webpack_require_189757__(93) var Minimatch = minimatch.Minimatch var inherits = __nested_webpack_require_189757__(689) var EE = __nested_webpack_require_189757__(614).EventEmitter var path = __nested_webpack_require_189757__(622) var assert = __nested_webpack_require_189757__(357) var isAbsolute = __nested_webpack_require_189757__(681) var globSync = __nested_webpack_require_189757__(245) var common = __nested_webpack_require_189757__(856) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __nested_webpack_require_189757__(674) var util = __nested_webpack_require_189757__(669) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nested_webpack_require_189757__(49) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 413: /***/ (function(module, __unusedexports, __nested_webpack_require_209348__) { module.exports = __nested_webpack_require_209348__(141); /***/ }), /***/ 417: /***/ (function(module) { module.exports = __webpack_require__(417); /***/ }), /***/ 431: /***/ (function(__unusedmodule, exports, __nested_webpack_require_209566__) { "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const os = __importStar(__nested_webpack_require_209566__(87)); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; function escapeData(s) { return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 470: /***/ (function(__unusedmodule, exports, __nested_webpack_require_212447__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const command_1 = __nested_webpack_require_212447__(431); const os = __importStar(__nested_webpack_require_212447__(87)); const path = __importStar(__nested_webpack_require_212447__(622)); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = command_1.toCommandValue(val); process.env[name] = convertedVal; command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { command_1.issueCommand('add-path', {}, inputPath); process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } return val.trim(); } exports.getInput = getInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { command_1.issue('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() */ function error(message) { command_1.issue('error', message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds an warning issue * @param message warning issue message. Errors will be converted to string via toString() */ function warning(message) { command_1.issue('warning', message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; //# sourceMappingURL=core.js.map /***/ }), /***/ 503: /***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function applyDefaults(options) { if (!options) { options = {}; } return { delay: (options.delay === undefined) ? 200 : options.delay, initialDelay: (options.initialDelay === undefined) ? 0 : options.initialDelay, minDelay: (options.minDelay === undefined) ? 0 : options.minDelay, maxDelay: (options.maxDelay === undefined) ? 0 : options.maxDelay, factor: (options.factor === undefined) ? 0 : options.factor, maxAttempts: (options.maxAttempts === undefined) ? 3 : options.maxAttempts, timeout: (options.timeout === undefined) ? 0 : options.timeout, jitter: (options.jitter === true), handleError: (options.handleError === undefined) ? null : options.handleError, handleTimeout: (options.handleTimeout === undefined) ? null : options.handleTimeout, beforeAttempt: (options.beforeAttempt === undefined) ? null : options.beforeAttempt, calculateDelay: (options.calculateDelay === undefined) ? null : options.calculateDelay }; } async function sleep(delay) { return new Promise((resolve, reject) => { setTimeout(resolve, delay); }); } exports.sleep = sleep; function defaultCalculateDelay(context, options) { let delay = options.delay; if (delay === 0) { // no delay between attempts return 0; } if (options.factor) { delay *= Math.pow(options.factor, context.attemptNum - 1); if (options.maxDelay !== 0) { delay = Math.min(delay, options.maxDelay); } } if (options.jitter) { // Jitter will result in a random value between `minDelay` and // calculated delay for a given attempt. // See https://www.awsarchitectureblog.com/2015/03/backoff.html // We're using the "full jitter" strategy. const min = Math.ceil(options.minDelay); const max = Math.floor(delay); delay = Math.floor(Math.random() * (max - min + 1)) + min; } return Math.round(delay); } exports.defaultCalculateDelay = defaultCalculateDelay; async function retry(attemptFunc, attemptOptions) { const options = applyDefaults(attemptOptions); for (const prop of [ 'delay', 'initialDelay', 'minDelay', 'maxDelay', 'maxAttempts', 'timeout' ]) { const value = options[prop]; if (!Number.isInteger(value) || (value < 0)) { throw new Error(`Value for ${prop} must be an integer greater than or equal to 0`); } } if ((options.factor.constructor !== Number) || (options.factor < 0)) { throw new Error(`Value for factor must be a number greater than or equal to 0`); } if (options.delay < options.minDelay) { throw new Error(`delay cannot be less than minDelay (delay: ${options.delay}, minDelay: ${options.minDelay}`); } const context = { attemptNum: 0, attemptsRemaining: options.maxAttempts ? options.maxAttempts : -1, aborted: false, abort() { context.aborted = true; } }; const calculateDelay = options.calculateDelay || defaultCalculateDelay; async function makeAttempt() { if (options.beforeAttempt) { options.beforeAttempt(context, options); } if (context.aborted) { const err = new Error(`Attempt aborted`); err.code = 'ATTEMPT_ABORTED'; throw err; } const onError = async (err) => { if (options.handleError) { options.handleError(err, context, options); } if (context.aborted || (context.attemptsRemaining === 0)) { throw err; } // We are about to try again so increment attempt number context.attemptNum++; const delay = calculateDelay(context, options); if (delay) { await sleep(delay); } return makeAttempt(); }; if (context.attemptsRemaining > 0) { context.attemptsRemaining--; } if (options.timeout) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { if (options.handleTimeout) { resolve(options.handleTimeout(context, options)); } else { const err = new Error(`Retry timeout (attemptNum: ${context.attemptNum}, timeout: ${options.timeout})`); err.code = 'ATTEMPT_TIMEOUT'; reject(err); } }, options.timeout); attemptFunc(context, options).then((result) => { clearTimeout(timer); resolve(result); }).catch((err) => { clearTimeout(timer); resolve(onError(err)); }); }); } else { // No timeout provided so wait indefinitely for the returned promise // to be resolved. return attemptFunc(context, options).catch(onError); } } const initialDelay = options.calculateDelay ? options.calculateDelay(context, options) : options.initialDelay; if (initialDelay) { await sleep(initialDelay); } return makeAttempt(); } exports.retry = retry; /***/ }), /***/ 533: /***/ (function(__unusedmodule, exports, __nested_webpack_require_225477__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__nested_webpack_require_225477__(470)); const io = __importStar(__nested_webpack_require_225477__(1)); const fs = __importStar(__nested_webpack_require_225477__(747)); const mm = __importStar(__nested_webpack_require_225477__(31)); const os = __importStar(__nested_webpack_require_225477__(87)); const path = __importStar(__nested_webpack_require_225477__(622)); const httpm = __importStar(__nested_webpack_require_225477__(539)); const semver = __importStar(__nested_webpack_require_225477__(280)); const stream = __importStar(__nested_webpack_require_225477__(794)); const util = __importStar(__nested_webpack_require_225477__(669)); const v4_1 = __importDefault(__nested_webpack_require_225477__(826)); const exec_1 = __nested_webpack_require_225477__(986); const assert_1 = __nested_webpack_require_225477__(357); const retry_helper_1 = __nested_webpack_require_225477__(979); class HTTPError extends Error { constructor(httpStatusCode) { super(`Unexpected HTTP response: ${httpStatusCode}`); this.httpStatusCode = httpStatusCode; Object.setPrototypeOf(this, new.target.prototype); } } exports.HTTPError = HTTPError; const IS_WINDOWS = process.platform === 'win32'; const userAgent = 'actions/tool-cache'; /** * Download a tool from an url and stream it into a file * * @param url url of tool to download * @param dest path to download tool * @param auth authorization header * @returns path to downloaded tool */ function downloadTool(url, dest, auth) { return __awaiter(this, void 0, void 0, function* () { dest = dest || path.join(_getTempDirectory(), v4_1.default()); yield io.mkdirP(path.dirname(dest)); core.debug(`Downloading ${url}`); core.debug(`Destination ${dest}`); const maxAttempts = 3; const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10); const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { return yield downloadToolAttempt(url, dest || '', auth); }), (err) => { if (err instanceof HTTPError && err.httpStatusCode) { // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests if (err.httpStatusCode < 500 && err.httpStatusCode !== 408 && err.httpStatusCode !== 429) { return false; } } // Otherwise retry return true; }); }); } exports.downloadTool = downloadTool; function downloadToolAttempt(url, dest, auth) { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } // Get the response headers const http = new httpm.HttpClient(userAgent, [], { allowRetries: false }); let headers; if (auth) { core.debug('set auth'); headers = { authorization: auth }; } const response = yield http.get(url, headers); if (response.message.statusCode !== 200) { const err = new HTTPError(response.message.statusCode); core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); throw err; } // Download the response body const pipeline = util.promisify(stream.pipeline); const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message); const readStream = responseMessageFactory(); let succeeded = false; try { yield pipeline(readStream, fs.createWriteStream(dest)); core.debug('download complete'); succeeded = true; return dest; } finally { // Error, delete dest before retry if (!succeeded) { core.debug('download failed'); try { yield io.rmRF(dest); } catch (err) { core.debug(`Failed to delete '${dest}'. ${err.message}`); } } } }); } /** * Extract a .7z file * * @param file path to the .7z file * @param dest destination directory. Optional. * @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this * problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will * gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is * bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line * interface, it is smaller than the full command line interface, and it does support long paths. At the * time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website. * Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path * to 7zr.exe can be pass to this function. * @returns path to the destination directory */ function extract7z(file, dest, _7zPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); assert_1.ok(file, 'parameter "file" is required'); dest = yield _createExtractFolder(dest); const originalCwd = process.cwd(); process.chdir(dest); if (_7zPath) { try { const logLevel = core.isDebug() ? '-bb1' : '-bb0'; const args = [ 'x', logLevel, '-bd', '-sccUTF-8', file ]; const options = { silent: true }; yield exec_1.exec(`"${_7zPath}"`, args, options); } finally { process.chdir(originalCwd); } } else { const escapedScript = path .join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1') .replace(/'/g, "''") .replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; const options = { silent: true }; try { const powershellPath = yield io.which('powershell', true); yield exec_1.exec(`"${powershellPath}"`, args, options); } finally { process.chdir(originalCwd); } } return dest; }); } exports.extract7z = extract7z; /** * Extract a compressed tar archive * * @param file path to the tar * @param dest destination directory. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional. * @returns path to the destination directory */ function extractTar(file, dest, flags = 'xz') { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } // Create dest dest = yield _createExtractFolder(dest); // Determine whether GNU tar core.debug('Checking tar --version'); let versionOutput = ''; yield exec_1.exec('tar --version', [], { ignoreReturnCode: true, silent: true, listeners: { stdout: (data) => (versionOutput += data.toString()), stderr: (data) => (versionOutput += data.toString()) } }); core.debug(versionOutput.trim()); const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); // Initialize args let args; if (flags instanceof Array) { args = flags; } else { args = [flags]; } if (core.isDebug() && !flags.includes('v')) { args.push('-v'); } let destArg = dest; let fileArg = file; if (IS_WINDOWS && isGnuTar) { args.push('--force-local'); destArg = dest.replace(/\\/g, '/'); // Technically only the dest needs to have `/` but for aesthetic consistency // convert slashes in the file arg too. fileArg = file.replace(/\\/g, '/'); } if (isGnuTar) { // Suppress warnings when using GNU tar to extract archives created by BSD tar args.push('--warning=no-unknown-keyword'); } args.push('-C', destArg, '-f', fileArg); yield exec_1.exec(`tar`, args); return dest; }); } exports.extractTar = extractTar; /** * Extract a zip * * @param file path to the zip * @param dest destination directory. Optional. * @returns path to the destination directory */ function extractZip(file, dest) { return __awaiter(this, void 0, void 0, function* () { if (!file) { throw new Error("parameter 'file' is required"); } dest = yield _createExtractFolder(dest); if (IS_WINDOWS) { yield extractZipWin(file, dest); } else { yield extractZipNix(file, dest); } return dest; }); } exports.extractZip = extractZip; function extractZipWin(file, dest) { return __awaiter(this, void 0, void 0, function* () { // build the powershell command const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; // run powershell const powershellPath = yield io.which('powershell', true); const args = [ '-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', command ]; yield exec_1.exec(`"${powershellPath}"`, args); }); } function extractZipNix(file, dest) { return __awaiter(this, void 0, void 0, function* () { const unzipPath = yield io.which('unzip', true); const args = [file]; if (!core.isDebug()) { args.unshift('-q'); } yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest }); }); } /** * Caches a directory and installs it into the tool cacheDir * * @param sourceDir the directory to cache into tools * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheDir(sourceDir, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source dir: ${sourceDir}`); if (!fs.statSync(sourceDir).isDirectory()) { throw new Error('sourceDir is not a directory'); } // Create the tool dir const destPath = yield _createToolPath(tool, version, arch); // copy each child item. do not move. move can fail on Windows // due to anti-virus software having an open handle on a file. for (const itemName of fs.readdirSync(sourceDir)) { const s = path.join(sourceDir, itemName); yield io.cp(s, destPath, { recursive: true }); } // write .complete _completeToolPath(tool, version, arch); return destPath; }); } exports.cacheDir = cacheDir; /** * Caches a downloaded file (GUID) and installs it * into the tool cache with a given targetName * * @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid. * @param targetFile the name of the file name in the tools directory * @param tool tool name * @param version version of the tool. semver format * @param arch architecture of the tool. Optional. Defaults to machine architecture */ function cacheFile(sourceFile, targetFile, tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { version = semver.clean(version) || version; arch = arch || os.arch(); core.debug(`Caching tool ${tool} ${version} ${arch}`); core.debug(`source file: ${sourceFile}`); if (!fs.statSync(sourceFile).isFile()) { throw new Error('sourceFile is not a file'); } // create the tool dir const destFolder = yield _createToolPath(tool, version, arch); // copy instead of move. move can fail on Windows due to // anti-virus software having an open handle on a file. const destPath = path.join(destFolder, targetFile); core.debug(`destination file ${destPath}`); yield io.cp(sourceFile, destPath); // write .complete _completeToolPath(tool, version, arch); return destFolder; }); } exports.cacheFile = cacheFile; /** * Finds the path to a tool version in the local installed tool cache * * @param toolName name of the tool * @param versionSpec version of the tool * @param arch optional arch. defaults to arch of computer */ function find(toolName, versionSpec, arch) { if (!toolName) { throw new Error('toolName parameter is required'); } if (!versionSpec) { throw new Error('versionSpec parameter is required'); } arch = arch || os.arch(); // attempt to resolve an explicit version if (!_isExplicitVersion(versionSpec)) { const localVersions = findAllVersions(toolName, arch); const match = _evaluateVersions(localVersions, versionSpec); versionSpec = match; } // check for the explicit version in the cache let toolPath = ''; if (versionSpec) { versionSpec = semver.clean(versionSpec) || ''; const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch); core.debug(`checking cache: ${cachePath}`); if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); toolPath = cachePath; } else { core.debug('not found'); } } return toolPath; } exports.find = find; /** * Finds the paths to all versions of a tool that are installed in the local tool cache * * @param toolName name of the tool * @param arch optional arch. defaults to arch of computer */ function findAllVersions(toolName, arch) { const versions = []; arch = arch || os.arch(); const toolPath = path.join(_getCacheDirectory(), toolName); if (fs.existsSync(toolPath)) { const children = fs.readdirSync(toolPath); for (const child of children) { if (_isExplicitVersion(child)) { const fullPath = path.join(toolPath, child, arch || ''); if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) { versions.push(child); } } } } return versions; } exports.findAllVersions = findAllVersions; function getManifestFromRepo(owner, repo, auth, branch = 'master') { return __awaiter(this, void 0, void 0, function* () { let releases = []; const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; const http = new httpm.HttpClient('tool-cache'); const headers = {}; if (auth) { core.debug('set auth'); headers.authorization = auth; } const response = yield http.getJson(treeUrl, headers); if (!response.result) { return releases; } let manifestUrl = ''; for (const item of response.result.tree) { if (item.path === 'versions-manifest.json') { manifestUrl = item.url; break; } } headers['accept'] = 'application/vnd.github.VERSION.raw'; let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); if (versionsRaw) { // shouldn't be needed but protects against invalid json saved with BOM versionsRaw = versionsRaw.replace(/^\uFEFF/, ''); try { releases = JSON.parse(versionsRaw); } catch (_a) { core.debug('Invalid json'); } } return releases; }); } exports.getManifestFromRepo = getManifestFromRepo; function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { return __awaiter(this, void 0, void 0, function* () { // wrap the internal impl const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); return match; }); } exports.findFromManifest = findFromManifest; function _createExtractFolder(dest) { return __awaiter(this, void 0, void 0, function* () { if (!dest) { // create a temp dir dest = path.join(_getTempDirectory(), v4_1.default()); } yield io.mkdirP(dest); return dest; }); } function _createToolPath(tool, version, arch) { return __awaiter(this, void 0, void 0, function* () { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); core.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io.rmRF(folderPath); yield io.rmRF(markerPath); yield io.mkdirP(folderPath); return folderPath; }); } function _completeToolPath(tool, version, arch) { const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || ''); const markerPath = `${folderPath}.complete`; fs.writeFileSync(markerPath, ''); core.debug('finished caching tool'); } function _isExplicitVersion(versionSpec) { const c = semver.clean(versionSpec) || ''; core.debug(`isExplicit: ${c}`); const valid = semver.valid(c) != null; core.debug(`explicit? ${valid}`); return valid; } function _evaluateVersions(versions, versionSpec) { let version = ''; core.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { if (semver.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; const satisfied = semver.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; } } if (version) { core.debug(`matched: ${version}`); } else { core.debug('match not found'); } return version; } /** * Gets RUNNER_TOOL_CACHE */ function _getCacheDirectory() { const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined'); return cacheDirectory; } /** * Gets RUNNER_TEMP */ function _getTempDirectory() { const tempDirectory = process.env['RUNNER_TEMP'] || ''; assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); return tempDirectory; } /** * Gets a global variable */ function _getGlobal(key, defaultValue) { /* eslint-disable @typescript-eslint/no-explicit-any */ const value = global[key]; /* eslint-enable @typescript-eslint/no-explicit-any */ return value !== undefined ? value : defaultValue; } //# sourceMappingURL=tool-cache.js.map /***/ }), /***/ 539: /***/ (function(__unusedmodule, exports, __nested_webpack_require_247584__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_247584__(835); const http = __nested_webpack_require_247584__(605); const https = __nested_webpack_require_247584__(211); const pm = __nested_webpack_require_247584__(950); let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise(async (resolve, reject) => { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ async getJson(requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ async request(verb, requestUrl, data, headers) { if (this._disposed) { throw new Error('Client has already been disposed.'); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { await response.readBody(); await this._performExponentialBackoff(numTries); } } return response; } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { let parsedUrl = url.parse(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; let proxyUrl = pm.getProxyUrl(parsedUrl); let useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __nested_webpack_require_247584__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } static dateTimeDeserializer(key, value) { if (typeof value === 'string') { let a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } async _processResponse(res, options) { return new Promise(async (resolve, reject) => { const statusCode = res.message.statusCode; const response = { statusCode: statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response); } let obj; let contents; // get the result from the body try { contents = await res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = 'Failed request: (' + statusCode + ')'; } let err = new Error(msg); // attach statusCode and body obj (if available) to the error object err['statusCode'] = statusCode; if (response.result) { err['result'] = response.result; } reject(err); } else { resolve(response); } }); } } exports.HttpClient = HttpClient; /***/ }), /***/ 569: /***/ (function(module, __unusedexports, __nested_webpack_require_270274__) { module.exports = rimraf rimraf.sync = rimrafSync var assert = __nested_webpack_require_270274__(357) var path = __nested_webpack_require_270274__(622) var fs = __nested_webpack_require_270274__(747) var glob = undefined try { glob = __nested_webpack_require_270274__(402) } catch (_err) { // treat glob as optional. } var _0666 = parseInt('666', 8) var defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling var timeout = 0 var isWindows = (process.platform === "win32") function defaults (options) { var methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(function(m) { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } function rimraf (p, options, cb) { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) var busyTries = 0 var errState = null var n = 0 if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, function (er, stat) { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) function next (er) { errState = errState || er if (--n === 0) cb(errState) } function afterGlob (er, results) { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(function (p) { rimraf_(p, options, function CB (er) { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ var time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(function () { rimraf_(p, options, CB) }, time) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(function () { rimraf_(p, options, CB) }, timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) }) }) } } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, function (er, st) { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, function (er) { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } function fixWinEPERM (p, options, er, cb) { assert(p) assert(options) assert(typeof cb === 'function') if (er) assert(er instanceof Error) options.chmod(p, _0666, function (er2) { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, function(er3, stats) { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } function fixWinEPERMSync (p, options, er) { assert(p) assert(options) if (er) assert(er instanceof Error) try { options.chmodSync(p, _0666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } try { var stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } function rmdir (p, options, originalEr, cb) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, function (er) { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } function rmkids(p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, function (er, files) { if (er) return cb(er) var n = files.length if (n === 0) return options.rmdir(p, cb) var errState files.forEach(function (f) { rimraf(path.join(p, f), options, function (er) { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p, options) { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') var results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (var i = 0; i < results.length; i++) { var p = results[i] try { var st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } function rmdirSync (p, options, originalEr) { assert(p) assert(options) if (originalEr) assert(originalEr instanceof Error) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } function rmkidsSync (p, options) { assert(p) assert(options) options.readdirSync(p).forEach(function (f) { rimrafSync(path.join(p, f), options) }) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. var retries = isWindows ? 100 : 1 var i = 0 do { var threw = true try { var ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } /***/ }), /***/ 581: /***/ (function(module) { "use strict"; var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, merge: merge }; /***/ }), /***/ 605: /***/ (function(module) { module.exports = __webpack_require__(605); /***/ }), /***/ 614: /***/ (function(module) { module.exports = __webpack_require__(614); /***/ }), /***/ 621: /***/ (function(module) { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 622: /***/ (function(module) { module.exports = __webpack_require__(622); /***/ }), /***/ 631: /***/ (function(module) { module.exports = __webpack_require__(631); /***/ }), /***/ 669: /***/ (function(module) { module.exports = __webpack_require__(669); /***/ }), /***/ 672: /***/ (function(__unusedmodule, exports, __nested_webpack_require_287959__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); const assert_1 = __nested_webpack_require_287959__(357); const fs = __nested_webpack_require_287959__(747); const path = __nested_webpack_require_287959__(622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Recursively create a directory at `fsPath`. * * This implementation is optimistic, meaning it attempts to create the full * path first, and backs up the path stack from there. * * @param fsPath The path to create * @param maxDepth The maximum recursion depth * @param depth The current recursion depth */ function mkdirP(fsPath, maxDepth = 1000, depth = 1) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); fsPath = path.resolve(fsPath); if (depth >= maxDepth) return exports.mkdir(fsPath); try { yield exports.mkdir(fsPath); return; } catch (err) { switch (err.code) { case 'ENOENT': { yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1); yield exports.mkdir(fsPath); return; } default: { let stats; try { stats = yield exports.stat(fsPath); } catch (err2) { throw err; } if (!stats.isDirectory()) throw err; } } } }); } exports.mkdirP = mkdirP; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } //# sourceMappingURL=io-util.js.map /***/ }), /***/ 674: /***/ (function(module, __unusedexports, __nested_webpack_require_295636__) { var wrappy = __nested_webpack_require_295636__(11) var reqs = Object.create(null) var once = __nested_webpack_require_295636__(49) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 681: /***/ (function(module) { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 689: /***/ (function(module, __unusedexports, __nested_webpack_require_297767__) { try { var util = __nested_webpack_require_297767__(669); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nested_webpack_require_297767__(315); } /***/ }), /***/ 722: /***/ (function(module) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 729: /***/ (function(__unusedmodule, exports, __nested_webpack_require_298933__) { "use strict"; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const qs = __nested_webpack_require_298933__(386); const url = __nested_webpack_require_298933__(835); const path = __nested_webpack_require_298933__(622); const zlib = __nested_webpack_require_298933__(761); /** * creates an url from a request url and optional base url (http://server:8080) * @param {string} resource - a fully qualified url or relative path * @param {string} baseUrl - an optional baseUrl (http://server:8080) * @param {IRequestOptions} options - an optional options object, could include QueryParameters e.g. * @return {string} - resultant url */ function getUrl(resource, baseUrl, queryParams) { const pathApi = path.posix || path; let requestUrl = ''; if (!baseUrl) { requestUrl = resource; } else if (!resource) { requestUrl = baseUrl; } else { const base = url.parse(baseUrl); const resultantUrl = url.parse(resource); // resource (specific per request) elements take priority resultantUrl.protocol = resultantUrl.protocol || base.protocol; resultantUrl.auth = resultantUrl.auth || base.auth; resultantUrl.host = resultantUrl.host || base.host; resultantUrl.pathname = pathApi.resolve(base.pathname, resultantUrl.pathname); if (!resultantUrl.pathname.endsWith('/') && resource.endsWith('/')) { resultantUrl.pathname += '/'; } requestUrl = url.format(resultantUrl); } return queryParams ? getUrlWithParsedQueryParams(requestUrl, queryParams) : requestUrl; } exports.getUrl = getUrl; /** * * @param {string} requestUrl * @param {IRequestQueryParams} queryParams * @return {string} - Request's URL with Query Parameters appended/parsed. */ function getUrlWithParsedQueryParams(requestUrl, queryParams) { const url = requestUrl.replace(/\?$/g, ''); // Clean any extra end-of-string "?" character const parsedQueryParams = qs.stringify(queryParams.params, buildParamsStringifyOptions(queryParams)); return `${url}${parsedQueryParams}`; } /** * Build options for QueryParams Stringifying. * * @param {IRequestQueryParams} queryParams * @return {object} */ function buildParamsStringifyOptions(queryParams) { let options = { addQueryPrefix: true, delimiter: (queryParams.options || {}).separator || '&', allowDots: (queryParams.options || {}).shouldAllowDots || false, arrayFormat: (queryParams.options || {}).arrayFormat || 'repeat', encodeValuesOnly: (queryParams.options || {}).shouldOnlyEncodeValues || true }; return options; } /** * Decompress/Decode gzip encoded JSON * Using Node.js built-in zlib module * * @param {Buffer} buffer * @param {string} charset? - optional; defaults to 'utf-8' * @return {Promise<string>} */ function decompressGzippedContent(buffer, charset) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { zlib.gunzip(buffer, function (error, buffer) { if (error) { reject(error); } resolve(buffer.toString(charset || 'utf-8')); }); })); }); } exports.decompressGzippedContent = decompressGzippedContent; /** * Obtain Response's Content Charset. * Through inspecting `content-type` response header. * It Returns 'utf-8' if NO charset specified/matched. * * @param {IHttpClientResponse} response * @return {string} - Content Encoding Charset; Default=utf-8 */ function obtainContentCharset(response) { // Find the charset, if specified. // Search for the `charset=CHARSET` string, not including `;,\r\n` // Example: content-type: 'application/json;charset=utf-8' // |__ matches would be ['charset=utf-8', 'utf-8', index: 18, input: 'application/json; charset=utf-8'] // |_____ matches[1] would have the charset :tada: , in our example it's utf-8 // However, if the matches Array was empty or no charset found, 'utf-8' would be returned by default. const nodeSupportedEncodings = ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'binary', 'hex']; const contentType = response.message.headers['content-type'] || ''; const matches = contentType.match(/charset=([^;,\r\n]+)/i); return (matches && matches[1] && nodeSupportedEncodings.indexOf(matches[1]) != -1) ? matches[1] : 'utf-8'; } exports.obtainContentCharset = obtainContentCharset; /***/ }), /***/ 747: /***/ (function(module) { module.exports = __webpack_require__(747); /***/ }), /***/ 755: /***/ (function(module, __unusedexports, __nested_webpack_require_304474__) { "use strict"; var utils = __nested_webpack_require_304474__(581); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = utils.maybeMap( parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; // eslint-disable-line no-param-reassign } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }), /***/ 761: /***/ (function(module) { module.exports = __webpack_require__(761); /***/ }), /***/ 794: /***/ (function(module) { module.exports = __webpack_require__(794); /***/ }), /***/ 826: /***/ (function(module, __unusedexports, __nested_webpack_require_313931__) { var rng = __nested_webpack_require_313931__(139); var bytesToUuid = __nested_webpack_require_313931__(722); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 835: /***/ (function(module) { module.exports = __webpack_require__(835); /***/ }), /***/ 856: /***/ (function(__unusedmodule, exports, __nested_webpack_require_314783__) { exports.alphasort = alphasort exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var path = __nested_webpack_require_314783__(622) var minimatch = __nested_webpack_require_314783__(93) var isAbsolute = __nested_webpack_require_314783__(681) var Minimatch = minimatch.Minimatch function alphasorti (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 874: /***/ (function(__unusedmodule, exports, __nested_webpack_require_321048__) { "use strict"; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_321048__(835); const http = __nested_webpack_require_321048__(605); const https = __nested_webpack_require_321048__(211); const util = __nested_webpack_require_321048__(729); let fs; let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect]; const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { let buffer = Buffer.alloc(0); const encodingCharset = util.obtainContentCharset(this); // Extract Encoding from header: 'content-encoding' // Match `gzip`, `gzip, deflate` variations of GZIP encoding const contentEncoding = this.message.headers['content-encoding'] || ''; const isGzippedEncoded = new RegExp('(gzip$)|(gzip, *deflate)').test(contentEncoding); this.message.on('data', function (data) { const chunk = (typeof data === 'string') ? Buffer.from(data, encodingCharset) : data; buffer = Buffer.concat([buffer, chunk]); }).on('end', function () { return __awaiter(this, void 0, void 0, function* () { if (isGzippedEncoded) { // Process GZipped Response Body HERE const gunzippedBody = yield util.decompressGzippedContent(buffer, encodingCharset); resolve(gunzippedBody); } else { resolve(buffer.toString(encodingCharset)); } }); }).on('error', function (err) { reject(err); }); })); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; var EnvironmentVariables; (function (EnvironmentVariables) { EnvironmentVariables["HTTP_PROXY"] = "HTTP_PROXY"; EnvironmentVariables["HTTPS_PROXY"] = "HTTPS_PROXY"; EnvironmentVariables["NO_PROXY"] = "NO_PROXY"; })(EnvironmentVariables || (EnvironmentVariables = {})); class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; let no_proxy = process.env[EnvironmentVariables.NO_PROXY]; if (no_proxy) { this._httpProxyBypassHosts = []; no_proxy.split(',').forEach(bypass => { this._httpProxyBypassHosts.push(new RegExp(bypass, 'i')); }); } this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; this._httpProxy = requestOptions.proxy; if (requestOptions.proxy && requestOptions.proxy.proxyBypassHosts) { this._httpProxyBypassHosts = []; requestOptions.proxy.proxyBypassHosts.forEach(bypass => { this._httpProxyBypassHosts.push(new RegExp(bypass, 'i')); }); } this._certConfig = requestOptions.cert; if (this._certConfig) { // If using cert, need fs fs = __nested_webpack_require_321048__(747); // cache the cert content into memory, so we don't have to read it from disk every time if (this._certConfig.caFile && fs.existsSync(this._certConfig.caFile)) { this._ca = fs.readFileSync(this._certConfig.caFile, 'utf8'); } if (this._certConfig.certFile && fs.existsSync(this._certConfig.certFile)) { this._cert = fs.readFileSync(this._certConfig.certFile, 'utf8'); } if (this._certConfig.keyFile && fs.existsSync(this._certConfig.keyFile)) { this._key = fs.readFileSync(this._certConfig.keyFile, 'utf8'); } } if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error("Client has already been disposed."); } let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers["location"]; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof (data) === 'string') { info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', (sock) => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.destroy(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof (data) === 'string') { req.write(data, 'utf8'); } if (data && typeof (data) !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers["user-agent"] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers && !this._isPresigned(url.format(requestUrl))) { this.handlers.forEach((handler) => { handler.prepareRequest(info.options); }); } return info; } _isPresigned(requestUrl) { if (this.requestOptions && this.requestOptions.presignedUrlPatterns) { const patterns = this.requestOptions.presignedUrlPatterns; for (let i = 0; i < patterns.length; i++) { if (requestUrl.match(patterns[i])) { return true; } } } return false; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getAgent(parsedUrl) { let agent; let proxy = this._getProxy(parsedUrl); let useProxy = proxy.proxyUrl && proxy.proxyUrl.hostname && !this._isMatchInBypassProxyList(parsedUrl); if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __nested_webpack_require_321048__(413); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { proxyAuth: proxy.proxyAuth, host: proxy.proxyUrl.hostname, port: proxy.proxyUrl.port }, }; let tunnelAgent; const overHttps = proxy.proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } if (usingSsl && this._certConfig) { agent.options = Object.assign(agent.options || {}, { ca: this._ca, cert: this._cert, key: this._key, passphrase: this._certConfig.passphrase }); } return agent; } _getProxy(parsedUrl) { let usingSsl = parsedUrl.protocol === 'https:'; let proxyConfig = this._httpProxy; // fallback to http_proxy and https_proxy env let https_proxy = process.env[EnvironmentVariables.HTTPS_PROXY]; let http_proxy = process.env[EnvironmentVariables.HTTP_PROXY]; if (!proxyConfig) { if (https_proxy && usingSsl) { proxyConfig = { proxyUrl: https_proxy }; } else if (http_proxy) { proxyConfig = { proxyUrl: http_proxy }; } } let proxyUrl; let proxyAuth; if (proxyConfig) { if (proxyConfig.proxyUrl.length > 0) { proxyUrl = url.parse(proxyConfig.proxyUrl); } if (proxyConfig.proxyUsername || proxyConfig.proxyPassword) { proxyAuth = proxyConfig.proxyUsername + ":" + proxyConfig.proxyPassword; } } return { proxyUrl: proxyUrl, proxyAuth: proxyAuth }; } _isMatchInBypassProxyList(parsedUrl) { if (!this._httpProxyBypassHosts) { return false; } let bypass = false; this._httpProxyBypassHosts.forEach(bypassHost => { if (bypassHost.test(parsedUrl.href)) { bypass = true; } }); return bypass; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } } exports.HttpClient = HttpClient; /***/ }), /***/ 896: /***/ (function(module) { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 897: /***/ (function(module, __unusedexports, __nested_webpack_require_343891__) { "use strict"; var utils = __nested_webpack_require_343891__(581); var formats = __nested_webpack_require_343891__(13); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var stringify = function stringify( object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }).join(','); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key'); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; var value = obj[key]; if (skipNulls && value === null) { continue; } var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? '.' + key : '[' + key + ']'); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.formatter, options.encodeValuesOnly, options.charset )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; /***/ }), /***/ 950: /***/ (function(__unusedmodule, exports, __nested_webpack_require_352018__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __nested_webpack_require_352018__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; if (checkBypass(reqUrl)) { return proxyUrl; } let proxyVar; if (usingSsl) { proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = url.parse(proxyVar); } return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port let upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (let upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; /***/ }), /***/ 962: /***/ (function(__unusedmodule, exports, __nested_webpack_require_353751__) { "use strict"; /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.installGcloudSDK = exports.GCLOUD_METRICS_LABEL = exports.GCLOUD_METRICS_ENV_VAR = void 0; /** * Contains installation utility functions. */ const toolCache = __importStar(__nested_webpack_require_353751__(533)); const core = __importStar(__nested_webpack_require_353751__(470)); const path_1 = __importDefault(__nested_webpack_require_353751__(622)); exports.GCLOUD_METRICS_ENV_VAR = 'CLOUDSDK_METRICS_ENVIRONMENT'; exports.GCLOUD_METRICS_LABEL = 'github-actions-setup-gcloud'; /** * Installs the gcloud SDK into the actions environment. * * @param version The version being installed. * @param gcloudExtPath The extraction path for the gcloud SDK. * @returns The path of the installed tool. */ function installGcloudSDK(version, gcloudExtPath) { return __awaiter(this, void 0, void 0, function* () { const toolRoot = path_1.default.join(gcloudExtPath, 'google-cloud-sdk'); let toolPath = yield toolCache.cacheDir(toolRoot, 'gcloud', version); toolPath = path_1.default.join(toolPath, 'bin'); core.addPath(toolPath); core.exportVariable(exports.GCLOUD_METRICS_ENV_VAR, exports.GCLOUD_METRICS_LABEL); return toolPath; }); } exports.installGcloudSDK = installGcloudSDK; /***/ }), /***/ 979: /***/ (function(__unusedmodule, exports, __nested_webpack_require_357361__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__nested_webpack_require_357361__(470)); /** * Internal class for retries */ class RetryHelper { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { throw new Error('max attempts should be greater than or equal to 1'); } this.maxAttempts = maxAttempts; this.minSeconds = Math.floor(minSeconds); this.maxSeconds = Math.floor(maxSeconds); if (this.minSeconds > this.maxSeconds) { throw new Error('min seconds should be less than or equal to max seconds'); } } execute(action, isRetryable) { return __awaiter(this, void 0, void 0, function* () { let attempt = 1; while (attempt < this.maxAttempts) { // Try try { return yield action(); } catch (err) { if (isRetryable && !isRetryable(err)) { throw err; } core.info(err.message); } // Sleep const seconds = this.getSleepAmount(); core.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } // Last attempt return yield action(); }); } getSleepAmount() { return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds); } sleep(seconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, seconds * 1000)); }); } } exports.RetryHelper = RetryHelper; //# sourceMappingURL=retry-helper.js.map /***/ }), /***/ 986: /***/ (function(__unusedmodule, exports, __nested_webpack_require_360288__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const tr = __importStar(__nested_webpack_require_360288__(9)); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise<number> exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; //# sourceMappingURL=exec.js.map /***/ }) /******/ }); /***/ }), /***/ 722: /***/ (function(module) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 738: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const core = __importStar(__webpack_require__(470)); const toolCache = __importStar(__webpack_require__(533)); const setupGcloud = __importStar(__webpack_require__(702)); const fs_1 = __webpack_require__(747); const path_1 = __importDefault(__webpack_require__(622)); const uuid_1 = __webpack_require__(898); function run() { return __awaiter(this, void 0, void 0, function* () { try { let version = core.getInput('version'); if (!version || version == 'latest') { version = yield setupGcloud.getLatestGcloudSDKVersion(); } // Install the gcloud if not already present if (!setupGcloud.isInstalled()) { yield setupGcloud.installGcloudSDK(version); } else { const toolPath = toolCache.find('gcloud', version); core.addPath(path_1.default.join(toolPath, 'bin')); } // Set the project ID, if given. const projectId = core.getInput('project_id'); if (projectId) { yield setupGcloud.setProject(projectId); core.info('Successfully set default project'); } const serviceAccountKey = core.getInput('service_account_key'); // If a service account key isn't provided, log an un-authenticated notice if (!serviceAccountKey) { core.info('No credentials provided, skipping authentication'); return; } else { yield setupGcloud.authenticateGcloudSDK(serviceAccountKey); } // Export credentials if requested - these credentials must be exported in // the shared workspace directory, since the filesystem must be shared among // all steps. const exportCreds = core.getInput('export_default_credentials'); if (String(exportCreds).toLowerCase() === 'true') { const workspace = process.env.GITHUB_WORKSPACE; if (!workspace) { throw new Error('Missing GITHUB_WORKSPACE!'); } const credsPath = path_1.default.join(workspace, uuid_1.v4()); const serviceAccountKeyObj = setupGcloud.parseServiceAccountKey(serviceAccountKey); yield fs_1.promises.writeFile(credsPath, JSON.stringify(serviceAccountKeyObj, null, 2)); core.exportVariable('GCLOUD_PROJECT', projectId ? projectId : serviceAccountKeyObj.project_id); // If projectId is set export it, else export projectId from SA core.exportVariable('GOOGLE_APPLICATION_CREDENTIALS', credsPath); core.info('Successfully exported Default Application Credentials'); } } catch (error) { core.setFailed(error.message); } }); } run(); /***/ }), /***/ 747: /***/ (function(module) { module.exports = require("fs"); /***/ }), /***/ 761: /***/ (function(module) { module.exports = require("zlib"); /***/ }), /***/ 794: /***/ (function(module) { module.exports = require("stream"); /***/ }), /***/ 826: /***/ (function(module, __unusedexports, __webpack_require__) { var rng = __webpack_require__(139); var bytesToUuid = __webpack_require__(722); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 835: /***/ (function(module) { module.exports = require("url"); /***/ }), /***/ 898: /***/ (function(module, __unusedexports, __webpack_require__) { var v1 = __webpack_require__(86); var v4 = __webpack_require__(826); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; /***/ }), /***/ 950: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; if (checkBypass(reqUrl)) { return proxyUrl; } let proxyVar; if (usingSsl) { proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = url.parse(proxyVar); } return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port let upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (let upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; /***/ }), /***/ 979: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); /** * Internal class for retries */ class RetryHelper { constructor(maxAttempts, minSeconds, maxSeconds) { if (maxAttempts < 1) { throw new Error('max attempts should be greater than or equal to 1'); } this.maxAttempts = maxAttempts; this.minSeconds = Math.floor(minSeconds); this.maxSeconds = Math.floor(maxSeconds); if (this.minSeconds > this.maxSeconds) { throw new Error('min seconds should be less than or equal to max seconds'); } } execute(action, isRetryable) { return __awaiter(this, void 0, void 0, function* () { let attempt = 1; while (attempt < this.maxAttempts) { // Try try { return yield action(); } catch (err) { if (isRetryable && !isRetryable(err)) { throw err; } core.info(err.message); } // Sleep const seconds = this.getSleepAmount(); core.info(`Waiting ${seconds} seconds before trying again`); yield this.sleep(seconds); attempt++; } // Last attempt return yield action(); }); } getSleepAmount() { return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds); } sleep(seconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, seconds * 1000)); }); } } exports.RetryHelper = RetryHelper; //# sourceMappingURL=retry-helper.js.map /***/ }), /***/ 986: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const tr = __webpack_require__(9); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise<number> exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; //# sourceMappingURL=exec.js.map /***/ }) /******/ });
chore: build dist
setup-gcloud/dist/index.js
chore: build dist
<ide><path>etup-gcloud/dist/index.js <ide> <ide> /***/ }), <ide> <add>/***/ 82: <add>/***/ (function(__unusedmodule, exports) { <add> <add>"use strict"; <add> <add>// We use any as a valid input type <add>/* eslint-disable @typescript-eslint/no-explicit-any */ <add>Object.defineProperty(exports, "__esModule", { value: true }); <add>/** <add> * Sanitizes an input into a string so it can be passed into issueCommand safely <add> * @param input input to sanitize into a string <add> */ <add>function toCommandValue(input) { <add> if (input === null || input === undefined) { <add> return ''; <add> } <add> else if (typeof input === 'string' || input instanceof String) { <add> return input; <add> } <add> return JSON.stringify(input); <add>} <add>exports.toCommandValue = toCommandValue; <add>//# sourceMappingURL=utils.js.map <add> <add>/***/ }), <add> <ide> /***/ 86: <ide> /***/ (function(module, __unusedexports, __webpack_require__) { <ide> <ide> <ide> /***/ }), <ide> <add>/***/ 102: <add>/***/ (function(__unusedmodule, exports, __webpack_require__) { <add> <add>"use strict"; <add> <add>// For internal use, subject to change. <add>var __importStar = (this && this.__importStar) || function (mod) { <add> if (mod && mod.__esModule) return mod; <add> var result = {}; <add> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; <add> result["default"] = mod; <add> return result; <add>}; <add>Object.defineProperty(exports, "__esModule", { value: true }); <add>// We use any as a valid input type <add>/* eslint-disable @typescript-eslint/no-explicit-any */ <add>const fs = __importStar(__webpack_require__(747)); <add>const os = __importStar(__webpack_require__(87)); <add>const utils_1 = __webpack_require__(82); <add>function issueCommand(command, message) { <add> const filePath = process.env[`GITHUB_${command}`]; <add> if (!filePath) { <add> throw new Error(`Unable to find environment variable for file command ${command}`); <add> } <add> if (!fs.existsSync(filePath)) { <add> throw new Error(`Missing file at path: ${filePath}`); <add> } <add> fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { <add> encoding: 'utf8' <add> }); <add>} <add>exports.issueCommand = issueCommand; <add>//# sourceMappingURL=file-command.js.map <add> <add>/***/ }), <add> <ide> /***/ 129: <ide> /***/ (function(module) { <ide> <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <ide> const os = __importStar(__webpack_require__(87)); <add>const utils_1 = __webpack_require__(82); <ide> /** <ide> * Commands <ide> * <ide> } <ide> } <ide> function escapeData(s) { <del> return (s || '') <add> return utils_1.toCommandValue(s) <ide> .replace(/%/g, '%25') <ide> .replace(/\r/g, '%0D') <ide> .replace(/\n/g, '%0A'); <ide> } <ide> function escapeProperty(s) { <del> return (s || '') <add> return utils_1.toCommandValue(s) <ide> .replace(/%/g, '%25') <ide> .replace(/\r/g, '%0D') <ide> .replace(/\n/g, '%0A') <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <ide> const command_1 = __webpack_require__(431); <add>const file_command_1 = __webpack_require__(102); <add>const utils_1 = __webpack_require__(82); <ide> const os = __importStar(__webpack_require__(87)); <ide> const path = __importStar(__webpack_require__(622)); <ide> /** <ide> /** <ide> * Sets env variable for this action and future actions in the job <ide> * @param name the name of the variable to set <del> * @param val the value of the variable <add> * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify <ide> */ <add>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function exportVariable(name, val) { <del> process.env[name] = val; <del> command_1.issueCommand('set-env', { name }, val); <add> const convertedVal = utils_1.toCommandValue(val); <add> process.env[name] = convertedVal; <add> const filePath = process.env['GITHUB_ENV'] || ''; <add> if (filePath) { <add> const delimiter = '_GitHubActionsFileCommandDelimeter_'; <add> const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; <add> file_command_1.issueCommand('ENV', commandValue); <add> } <add> else { <add> command_1.issueCommand('set-env', { name }, convertedVal); <add> } <ide> } <ide> exports.exportVariable = exportVariable; <ide> /** <ide> * @param inputPath <ide> */ <ide> function addPath(inputPath) { <del> command_1.issueCommand('add-path', {}, inputPath); <add> const filePath = process.env['GITHUB_PATH'] || ''; <add> if (filePath) { <add> file_command_1.issueCommand('PATH', inputPath); <add> } <add> else { <add> command_1.issueCommand('add-path', {}, inputPath); <add> } <ide> process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; <ide> } <ide> exports.addPath = addPath; <ide> * Sets the value of an output. <ide> * <ide> * @param name name of the output to set <del> * @param value value to store <add> * @param value value to store. Non-string values will be converted to a string via JSON.stringify <ide> */ <add>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function setOutput(name, value) { <ide> command_1.issueCommand('set-output', { name }, value); <ide> } <ide> exports.setOutput = setOutput; <add>/** <add> * Enables or disables the echoing of commands into stdout for the rest of the step. <add> * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. <add> * <add> */ <add>function setCommandEcho(enabled) { <add> command_1.issue('echo', enabled ? 'on' : 'off'); <add>} <add>exports.setCommandEcho = setCommandEcho; <ide> //----------------------------------------------------------------------- <ide> // Results <ide> //----------------------------------------------------------------------- <ide> exports.debug = debug; <ide> /** <ide> * Adds an error issue <del> * @param message error issue message <add> * @param message error issue message. Errors will be converted to string via toString() <ide> */ <ide> function error(message) { <del> command_1.issue('error', message); <add> command_1.issue('error', message instanceof Error ? message.toString() : message); <ide> } <ide> exports.error = error; <ide> /** <ide> * Adds an warning issue <del> * @param message warning issue message <add> * @param message warning issue message. Errors will be converted to string via toString() <ide> */ <ide> function warning(message) { <del> command_1.issue('warning', message); <add> command_1.issue('warning', message instanceof Error ? message.toString() : message); <ide> } <ide> exports.warning = warning; <ide> /** <ide> * Saves state for current action, the state can only be retrieved by this action's post job execution. <ide> * <ide> * @param name name of the state to store <del> * @param value value to store <add> * @param value value to store. Non-string values will be converted to a string via JSON.stringify <ide> */ <add>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function saveState(name, value) { <ide> command_1.issueCommand('save-state', { name }, value); <ide> } <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); <del>}) : (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> o[k2] = m[k]; <del>})); <del>var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { <del> Object.defineProperty(o, "default", { enumerable: true, value: v }); <del>}) : function(o, v) { <del> o["default"] = v; <del>}); <del>var __importStar = (this && this.__importStar) || function (mod) { <del> if (mod && mod.__esModule) return mod; <del> var result = {}; <del> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); <del> __setModuleDefault(result, mod); <del> return result; <del>}; <ide> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <ide> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <ide> return new (P || (P = Promise))(function (resolve, reject) { <ide> step((generator = generator.apply(thisArg, _arguments || [])).next()); <ide> }); <ide> }; <add>var __importStar = (this && this.__importStar) || function (mod) { <add> if (mod && mod.__esModule) return mod; <add> var result = {}; <add> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; <add> result["default"] = mod; <add> return result; <add>}; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>exports.getReleaseURL = void 0; <ide> const httpm = __importStar(__nested_webpack_require_13050__(874)); <ide> const attempt_1 = __nested_webpack_require_13050__(503); <ide> const install_util_1 = __nested_webpack_require_13050__(962); <ide> /***/ }), <ide> <ide> /***/ 9: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_17825__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_17245__) { <ide> <ide> "use strict"; <ide> <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const os = __importStar(__nested_webpack_require_17825__(87)); <del>const events = __importStar(__nested_webpack_require_17825__(614)); <del>const child = __importStar(__nested_webpack_require_17825__(129)); <del>const path = __importStar(__nested_webpack_require_17825__(622)); <del>const io = __importStar(__nested_webpack_require_17825__(1)); <del>const ioUtil = __importStar(__nested_webpack_require_17825__(672)); <add>const os = __importStar(__nested_webpack_require_17245__(87)); <add>const events = __importStar(__nested_webpack_require_17245__(614)); <add>const child = __importStar(__nested_webpack_require_17245__(129)); <add>const path = __importStar(__nested_webpack_require_17245__(622)); <add>const io = __importStar(__nested_webpack_require_17245__(1)); <add>const ioUtil = __importStar(__nested_webpack_require_17245__(672)); <ide> /* eslint-disable @typescript-eslint/unbound-method */ <ide> const IS_WINDOWS = process.platform === 'win32'; <ide> /* <ide> /***/ }), <ide> <ide> /***/ 13: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_43219__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_42639__) { <ide> <ide> "use strict"; <ide> <ide> var replace = String.prototype.replace; <ide> var percentTwenties = /%20/g; <ide> <del>var util = __nested_webpack_require_43219__(581); <add>var util = __nested_webpack_require_42639__(581); <ide> <ide> var Format = { <ide> RFC1738: 'RFC1738', <ide> <ide> /***/ }), <ide> <del>/***/ 31: <del>/***/ (function(module, exports, __nested_webpack_require_43909__) { <add>/***/ 49: <add>/***/ (function(module, __unusedexports, __nested_webpack_require_43337__) { <add> <add>var wrappy = __nested_webpack_require_43337__(11) <add>module.exports = wrappy(once) <add>module.exports.strict = wrappy(onceStrict) <add> <add>once.proto = once(function () { <add> Object.defineProperty(Function.prototype, 'once', { <add> value: function () { <add> return once(this) <add> }, <add> configurable: true <add> }) <add> <add> Object.defineProperty(Function.prototype, 'onceStrict', { <add> value: function () { <add> return onceStrict(this) <add> }, <add> configurable: true <add> }) <add>}) <add> <add>function once (fn) { <add> var f = function () { <add> if (f.called) return f.value <add> f.called = true <add> return f.value = fn.apply(this, arguments) <add> } <add> f.called = false <add> return f <add>} <add> <add>function onceStrict (fn) { <add> var f = function () { <add> if (f.called) <add> throw new Error(f.onceError) <add> f.called = true <add> return f.value = fn.apply(this, arguments) <add> } <add> var name = fn.name || 'Function wrapped with `once`' <add> f.onceError = name + " shouldn't be called more than once" <add> f.called = false <add> return f <add>} <add> <add> <add>/***/ }), <add> <add>/***/ 71: <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_44366__) { <ide> <ide> "use strict"; <ide> <add>/* <add> * Copyright 2020 Google LLC <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <ide> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <ide> return new (P || (P = Promise))(function (resolve, reject) { <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const semver = __importStar(__nested_webpack_require_43909__(280)); <del>const core_1 = __nested_webpack_require_43909__(470); <del>// needs to be require for core node modules to be mocked <del>/* eslint @typescript-eslint/no-require-imports: 0 */ <del>const os = __nested_webpack_require_43909__(87); <del>const cp = __nested_webpack_require_43909__(129); <del>const fs = __nested_webpack_require_43909__(747); <del>function _findMatch(versionSpec, stable, candidates, archFilter) { <del> return __awaiter(this, void 0, void 0, function* () { <del> const platFilter = os.platform(); <del> let result; <del> let match; <del> let file; <del> for (const candidate of candidates) { <del> const version = candidate.version; <del> core_1.debug(`check ${version} satisfies ${versionSpec}`); <del> if (semver.satisfies(version, versionSpec) && <del> (!stable || candidate.stable === stable)) { <del> file = candidate.files.find(item => { <del> core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); <del> let chk = item.arch === archFilter && item.platform === platFilter; <del> if (chk && item.platform_version) { <del> const osVersion = module.exports._getOsVersion(); <del> if (osVersion === item.platform_version) { <del> chk = true; <del> } <del> else { <del> chk = semver.satisfies(osVersion, item.platform_version); <del> } <del> } <del> return chk; <del> }); <del> if (file) { <del> core_1.debug(`matched ${candidate.version}`); <del> match = candidate; <del> break; <del> } <del> } <del> } <del> if (match && file) { <del> // clone since we're mutating the file list to be only the file that matches <del> result = Object.assign({}, match); <del> result.files = [file]; <del> } <del> return result; <del> }); <del>} <del>exports._findMatch = _findMatch; <del>function _getOsVersion() { <del> // TODO: add windows and other linux, arm variants <del> // right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python) <del> const plat = os.platform(); <del> let version = ''; <del> if (plat === 'darwin') { <del> version = cp.execSync('sw_vers -productVersion').toString(); <del> } <del> else if (plat === 'linux') { <del> // lsb_release process not in some containers, readfile <del> // Run cat /etc/lsb-release <del> // DISTRIB_ID=Ubuntu <del> // DISTRIB_RELEASE=18.04 <del> // DISTRIB_CODENAME=bionic <del> // DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS" <del> const lsbContents = module.exports._readLinuxVersionFile(); <del> if (lsbContents) { <del> const lines = lsbContents.split('\n'); <del> for (const line of lines) { <del> const parts = line.split('='); <del> if (parts.length === 2 && parts[0].trim() === 'DISTRIB_RELEASE') { <del> version = parts[1].trim(); <del> break; <del> } <del> } <del> } <del> } <del> return version; <del>} <del>exports._getOsVersion = _getOsVersion; <del>function _readLinuxVersionFile() { <del> const lsbFile = '/etc/lsb-release'; <del> let contents = ''; <del> if (fs.existsSync(lsbFile)) { <del> contents = fs.readFileSync(lsbFile).toString(); <del> } <del> return contents; <del>} <del>exports._readLinuxVersionFile = _readLinuxVersionFile; <del>//# sourceMappingURL=manifest.js.map <del> <del>/***/ }), <del> <del>/***/ 49: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_48507__) { <del> <del>var wrappy = __nested_webpack_require_48507__(11) <del>module.exports = wrappy(once) <del>module.exports.strict = wrappy(onceStrict) <del> <del>once.proto = once(function () { <del> Object.defineProperty(Function.prototype, 'once', { <del> value: function () { <del> return once(this) <del> }, <del> configurable: true <del> }) <del> <del> Object.defineProperty(Function.prototype, 'onceStrict', { <del> value: function () { <del> return onceStrict(this) <del> }, <del> configurable: true <del> }) <del>}) <del> <del>function once (fn) { <del> var f = function () { <del> if (f.called) return f.value <del> f.called = true <del> return f.value = fn.apply(this, arguments) <del> } <del> f.called = false <del> return f <del>} <del> <del>function onceStrict (fn) { <del> var f = function () { <del> if (f.called) <del> throw new Error(f.onceError) <del> f.called = true <del> return f.value = fn.apply(this, arguments) <del> } <del> var name = fn.name || 'Function wrapped with `once`' <del> f.onceError = name + " shouldn't be called more than once" <del> f.called = false <del> return f <del>} <del> <del> <del>/***/ }), <del> <del>/***/ 71: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_49536__) { <del> <del>"use strict"; <del> <del>/* <del> * Copyright 2020 Google LLC <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); <del>}) : (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> o[k2] = m[k]; <del>})); <del>var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { <del> Object.defineProperty(o, "default", { enumerable: true, value: v }); <del>}) : function(o, v) { <del> o["default"] = v; <del>}); <del>var __importStar = (this && this.__importStar) || function (mod) { <del> if (mod && mod.__esModule) return mod; <del> var result = {}; <del> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); <del> __setModuleDefault(result, mod); <del> return result; <del>}; <del>var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <del> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <del> return new (P || (P = Promise))(function (resolve, reject) { <del> function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } <del> function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } <del> function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } <del> step((generator = generator.apply(thisArg, _arguments || [])).next()); <del> }); <del>}; <del>Object.defineProperty(exports, "__esModule", { value: true }); <del>exports.getLatestGcloudSDKVersion = void 0; <ide> /** <ide> * Contains version utility functions. <ide> */ <del>const httpm = __importStar(__nested_webpack_require_49536__(874)); <del>const attempt_1 = __nested_webpack_require_49536__(503); <del>const install_util_1 = __nested_webpack_require_49536__(962); <add>const httpm = __importStar(__nested_webpack_require_44366__(874)); <add>const attempt_1 = __nested_webpack_require_44366__(503); <add>const install_util_1 = __nested_webpack_require_44366__(962); <ide> /** <ide> * @returns The latest stable version of the gcloud SDK. <ide> */ <ide> /***/ }), <ide> <ide> /***/ 93: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_53285__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_47523__) { <ide> <ide> module.exports = minimatch <ide> minimatch.Minimatch = Minimatch <ide> <ide> var path = { sep: '/' } <ide> try { <del> path = __nested_webpack_require_53285__(622) <add> path = __nested_webpack_require_47523__(622) <ide> } catch (er) {} <ide> <ide> var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} <del>var expand = __nested_webpack_require_53285__(306) <add>var expand = __nested_webpack_require_47523__(306) <ide> <ide> var plTypes = { <ide> '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, <ide> /***/ }), <ide> <ide> /***/ 117: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_78728__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_72966__) { <ide> <ide> // Copyright Joyent, Inc. and other Node contributors. <ide> // <ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <del>var pathModule = __nested_webpack_require_78728__(622); <add>var pathModule = __nested_webpack_require_72966__(622); <ide> var isWindows = process.platform === 'win32'; <del>var fs = __nested_webpack_require_78728__(747); <add>var fs = __nested_webpack_require_72966__(747); <ide> <ide> // JavaScript implementation of realpath, ported from node pre-v6 <ide> <ide> /***/ }), <ide> <ide> /***/ 139: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_87472__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_81710__) { <ide> <ide> // Unique ID creation requires a high quality random # generator. In node.js <ide> // this is pretty straight-forward - we use the crypto API. <ide> <del>var crypto = __nested_webpack_require_87472__(417); <add>var crypto = __nested_webpack_require_81710__(417); <ide> <ide> module.exports = function nodeRNG() { <ide> return crypto.randomBytes(16); <ide> /***/ }), <ide> <ide> /***/ 141: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_87814__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_82052__) { <ide> <ide> "use strict"; <ide> <ide> <del>var net = __nested_webpack_require_87814__(631); <del>var tls = __nested_webpack_require_87814__(16); <del>var http = __nested_webpack_require_87814__(605); <del>var https = __nested_webpack_require_87814__(211); <del>var events = __nested_webpack_require_87814__(614); <del>var assert = __nested_webpack_require_87814__(357); <del>var util = __nested_webpack_require_87814__(669); <add>var net = __nested_webpack_require_82052__(631); <add>var tls = __nested_webpack_require_82052__(16); <add>var http = __nested_webpack_require_82052__(605); <add>var https = __nested_webpack_require_82052__(211); <add>var events = __nested_webpack_require_82052__(614); <add>var assert = __nested_webpack_require_82052__(357); <add>var util = __nested_webpack_require_82052__(669); <ide> <ide> <ide> exports.httpOverHttp = httpOverHttp; <ide> /***/ }), <ide> <ide> /***/ 150: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_95591__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_89829__) { <ide> <ide> /*! <ide> * Tmp <ide> /* <ide> * Module dependencies. <ide> */ <del>const fs = __nested_webpack_require_95591__(747); <del>const os = __nested_webpack_require_95591__(87); <del>const path = __nested_webpack_require_95591__(622); <del>const crypto = __nested_webpack_require_95591__(417); <add>const fs = __nested_webpack_require_89829__(747); <add>const os = __nested_webpack_require_89829__(87); <add>const path = __nested_webpack_require_89829__(622); <add>const crypto = __nested_webpack_require_89829__(417); <ide> const _c = fs.constants && os.constants ? <ide> { fs: fs.constants, os: os.constants } : <ide> process.binding('constants'); <del>const rimraf = __nested_webpack_require_95591__(569); <add>const rimraf = __nested_webpack_require_89829__(569); <ide> <ide> /* <ide> * The working inner variables. <ide> /***/ }), <ide> <ide> /***/ 245: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_115426__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_109664__) { <ide> <ide> module.exports = globSync <ide> globSync.GlobSync = GlobSync <ide> <del>var fs = __nested_webpack_require_115426__(747) <del>var rp = __nested_webpack_require_115426__(302) <del>var minimatch = __nested_webpack_require_115426__(93) <add>var fs = __nested_webpack_require_109664__(747) <add>var rp = __nested_webpack_require_109664__(302) <add>var minimatch = __nested_webpack_require_109664__(93) <ide> var Minimatch = minimatch.Minimatch <del>var Glob = __nested_webpack_require_115426__(402).Glob <del>var util = __nested_webpack_require_115426__(669) <del>var path = __nested_webpack_require_115426__(622) <del>var assert = __nested_webpack_require_115426__(357) <del>var isAbsolute = __nested_webpack_require_115426__(681) <del>var common = __nested_webpack_require_115426__(856) <add>var Glob = __nested_webpack_require_109664__(402).Glob <add>var util = __nested_webpack_require_109664__(669) <add>var path = __nested_webpack_require_109664__(622) <add>var assert = __nested_webpack_require_109664__(357) <add>var isAbsolute = __nested_webpack_require_109664__(681) <add>var common = __nested_webpack_require_109664__(856) <ide> var alphasort = common.alphasort <ide> var alphasorti = common.alphasorti <ide> var setopts = common.setopts <ide> /***/ }), <ide> <ide> /***/ 302: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_169751__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_163989__) { <ide> <ide> module.exports = realpath <ide> realpath.realpath = realpath <ide> realpath.monkeypatch = monkeypatch <ide> realpath.unmonkeypatch = unmonkeypatch <ide> <del>var fs = __nested_webpack_require_169751__(747) <add>var fs = __nested_webpack_require_163989__(747) <ide> var origRealpath = fs.realpath <ide> var origRealpathSync = fs.realpathSync <ide> <ide> var version = process.version <ide> var ok = /^v[0-5]\./.test(version) <del>var old = __nested_webpack_require_169751__(117) <add>var old = __nested_webpack_require_163989__(117) <ide> <ide> function newError (er) { <ide> return er && er.syscall === 'realpath' && ( <ide> /***/ }), <ide> <ide> /***/ 306: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_171164__) { <del> <del>var concatMap = __nested_webpack_require_171164__(896); <del>var balanced = __nested_webpack_require_171164__(621); <add>/***/ (function(module, __unusedexports, __nested_webpack_require_165402__) { <add> <add>var concatMap = __nested_webpack_require_165402__(896); <add>var balanced = __nested_webpack_require_165402__(621); <ide> <ide> module.exports = expandTop; <ide> <ide> /***/ }), <ide> <ide> /***/ 325: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_176851__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_171089__) { <ide> <ide> "use strict"; <ide> <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); <del>}) : (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> o[k2] = m[k]; <del>})); <del>var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { <del> Object.defineProperty(o, "default", { enumerable: true, value: v }); <del>}) : function(o, v) { <del> o["default"] = v; <del>}); <del>var __importStar = (this && this.__importStar) || function (mod) { <del> if (mod && mod.__esModule) return mod; <del> var result = {}; <del> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); <del> __setModuleDefault(result, mod); <del> return result; <del>}; <ide> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <ide> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <ide> return new (P || (P = Promise))(function (resolve, reject) { <ide> step((generator = generator.apply(thisArg, _arguments || [])).next()); <ide> }); <ide> }; <add>var __importStar = (this && this.__importStar) || function (mod) { <add> if (mod && mod.__esModule) return mod; <add> var result = {}; <add> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; <add> result["default"] = mod; <add> return result; <add>}; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>exports.setProjectWithKey = exports.setProject = exports.authenticateGcloudSDK = exports.parseServiceAccountKey = exports.installGcloudSDK = exports.isAuthenticated = exports.isProjectIdSet = exports.getToolCommand = exports.isInstalled = exports.getLatestGcloudSDKVersion = void 0; <del>const exec = __importStar(__nested_webpack_require_176851__(986)); <del>const toolCache = __importStar(__nested_webpack_require_176851__(533)); <del>const os = __importStar(__nested_webpack_require_176851__(87)); <del>const tmp = __importStar(__nested_webpack_require_176851__(150)); <del>const format_url_1 = __nested_webpack_require_176851__(8); <del>const downloadUtil = __importStar(__nested_webpack_require_176851__(339)); <del>const installUtil = __importStar(__nested_webpack_require_176851__(962)); <del>const version_util_1 = __nested_webpack_require_176851__(71); <del>Object.defineProperty(exports, "getLatestGcloudSDKVersion", { enumerable: true, get: function () { return version_util_1.getLatestGcloudSDKVersion; } }); <add>const exec = __importStar(__nested_webpack_require_171089__(986)); <add>const toolCache = __importStar(__nested_webpack_require_171089__(533)); <add>const os = __importStar(__nested_webpack_require_171089__(87)); <add>const tmp = __importStar(__nested_webpack_require_171089__(150)); <add>const format_url_1 = __nested_webpack_require_171089__(8); <add>const downloadUtil = __importStar(__nested_webpack_require_171089__(339)); <add>const installUtil = __importStar(__nested_webpack_require_171089__(962)); <add>const version_util_1 = __nested_webpack_require_171089__(71); <add>exports.getLatestGcloudSDKVersion = version_util_1.getLatestGcloudSDKVersion; <ide> /** <ide> * Checks if gcloud is installed. <ide> * <ide> /***/ }), <ide> <ide> /***/ 339: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_185781__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_179112__) { <ide> <ide> "use strict"; <ide> <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); <del>}) : (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> o[k2] = m[k]; <del>})); <del>var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { <del> Object.defineProperty(o, "default", { enumerable: true, value: v }); <del>}) : function(o, v) { <del> o["default"] = v; <del>}); <del>var __importStar = (this && this.__importStar) || function (mod) { <del> if (mod && mod.__esModule) return mod; <del> var result = {}; <del> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); <del> __setModuleDefault(result, mod); <del> return result; <del>}; <ide> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <ide> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <ide> return new (P || (P = Promise))(function (resolve, reject) { <ide> step((generator = generator.apply(thisArg, _arguments || [])).next()); <ide> }); <ide> }; <add>var __importStar = (this && this.__importStar) || function (mod) { <add> if (mod && mod.__esModule) return mod; <add> var result = {}; <add> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; <add> result["default"] = mod; <add> return result; <add>}; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>exports.downloadAndExtractTool = void 0; <ide> /** <ide> * Contains download utility functions. <ide> */ <del>const toolCache = __importStar(__nested_webpack_require_185781__(533)); <del>const attempt_1 = __nested_webpack_require_185781__(503); <add>const toolCache = __importStar(__nested_webpack_require_179112__(533)); <add>const attempt_1 = __nested_webpack_require_179112__(503); <ide> /** <ide> * Downloads and extracts the tool at the specified URL. <ide> * <ide> /***/ }), <ide> <ide> /***/ 386: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_189445__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_182187__) { <ide> <ide> "use strict"; <ide> <ide> <del>var stringify = __nested_webpack_require_189445__(897); <del>var parse = __nested_webpack_require_189445__(755); <del>var formats = __nested_webpack_require_189445__(13); <add>var stringify = __nested_webpack_require_182187__(897); <add>var parse = __nested_webpack_require_182187__(755); <add>var formats = __nested_webpack_require_182187__(13); <ide> <ide> module.exports = { <ide> formats: formats, <ide> /***/ }), <ide> <ide> /***/ 402: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_189757__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_182499__) { <ide> <ide> // Approach: <ide> // <ide> <ide> module.exports = glob <ide> <del>var fs = __nested_webpack_require_189757__(747) <del>var rp = __nested_webpack_require_189757__(302) <del>var minimatch = __nested_webpack_require_189757__(93) <add>var fs = __nested_webpack_require_182499__(747) <add>var rp = __nested_webpack_require_182499__(302) <add>var minimatch = __nested_webpack_require_182499__(93) <ide> var Minimatch = minimatch.Minimatch <del>var inherits = __nested_webpack_require_189757__(689) <del>var EE = __nested_webpack_require_189757__(614).EventEmitter <del>var path = __nested_webpack_require_189757__(622) <del>var assert = __nested_webpack_require_189757__(357) <del>var isAbsolute = __nested_webpack_require_189757__(681) <del>var globSync = __nested_webpack_require_189757__(245) <del>var common = __nested_webpack_require_189757__(856) <add>var inherits = __nested_webpack_require_182499__(689) <add>var EE = __nested_webpack_require_182499__(614).EventEmitter <add>var path = __nested_webpack_require_182499__(622) <add>var assert = __nested_webpack_require_182499__(357) <add>var isAbsolute = __nested_webpack_require_182499__(681) <add>var globSync = __nested_webpack_require_182499__(245) <add>var common = __nested_webpack_require_182499__(856) <ide> var alphasort = common.alphasort <ide> var alphasorti = common.alphasorti <ide> var setopts = common.setopts <ide> var ownProp = common.ownProp <del>var inflight = __nested_webpack_require_189757__(674) <del>var util = __nested_webpack_require_189757__(669) <add>var inflight = __nested_webpack_require_182499__(674) <add>var util = __nested_webpack_require_182499__(669) <ide> var childrenIgnored = common.childrenIgnored <ide> var isIgnored = common.isIgnored <ide> <del>var once = __nested_webpack_require_189757__(49) <add>var once = __nested_webpack_require_182499__(49) <ide> <ide> function glob (pattern, options, cb) { <ide> if (typeof options === 'function') cb = options, options = {} <ide> /***/ }), <ide> <ide> /***/ 413: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_209348__) { <del> <del>module.exports = __nested_webpack_require_209348__(141); <add>/***/ (function(module, __unusedexports, __nested_webpack_require_202090__) { <add> <add>module.exports = __nested_webpack_require_202090__(141); <ide> <ide> <ide> /***/ }), <ide> /***/ }), <ide> <ide> /***/ 431: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_209566__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_202308__) { <ide> <ide> "use strict"; <ide> <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const os = __importStar(__nested_webpack_require_209566__(87)); <add>const os = __importStar(__nested_webpack_require_202308__(87)); <ide> /** <ide> * Commands <ide> * <ide> return cmdStr; <ide> } <ide> } <del>/** <del> * Sanitizes an input into a string so it can be passed into issueCommand safely <del> * @param input input to sanitize into a string <del> */ <del>function toCommandValue(input) { <del> if (input === null || input === undefined) { <del> return ''; <del> } <del> else if (typeof input === 'string' || input instanceof String) { <del> return input; <del> } <del> return JSON.stringify(input); <del>} <del>exports.toCommandValue = toCommandValue; <ide> function escapeData(s) { <del> return toCommandValue(s) <add> return (s || '') <ide> .replace(/%/g, '%25') <ide> .replace(/\r/g, '%0D') <ide> .replace(/\n/g, '%0A'); <ide> } <ide> function escapeProperty(s) { <del> return toCommandValue(s) <add> return (s || '') <ide> .replace(/%/g, '%25') <ide> .replace(/\r/g, '%0D') <ide> .replace(/\n/g, '%0A') <ide> /***/ }), <ide> <ide> /***/ 470: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_212447__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_204755__) { <ide> <ide> "use strict"; <ide> <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const command_1 = __nested_webpack_require_212447__(431); <del>const os = __importStar(__nested_webpack_require_212447__(87)); <del>const path = __importStar(__nested_webpack_require_212447__(622)); <add>const command_1 = __nested_webpack_require_204755__(431); <add>const os = __importStar(__nested_webpack_require_204755__(87)); <add>const path = __importStar(__nested_webpack_require_204755__(622)); <ide> /** <ide> * The code to exit an action <ide> */ <ide> /** <ide> * Sets env variable for this action and future actions in the job <ide> * @param name the name of the variable to set <del> * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify <add> * @param val the value of the variable <ide> */ <del>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function exportVariable(name, val) { <del> const convertedVal = command_1.toCommandValue(val); <del> process.env[name] = convertedVal; <del> command_1.issueCommand('set-env', { name }, convertedVal); <add> process.env[name] = val; <add> command_1.issueCommand('set-env', { name }, val); <ide> } <ide> exports.exportVariable = exportVariable; <ide> /** <ide> * Sets the value of an output. <ide> * <ide> * @param name name of the output to set <del> * @param value value to store. Non-string values will be converted to a string via JSON.stringify <add> * @param value value to store <ide> */ <del>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function setOutput(name, value) { <ide> command_1.issueCommand('set-output', { name }, value); <ide> } <ide> exports.setOutput = setOutput; <del>/** <del> * Enables or disables the echoing of commands into stdout for the rest of the step. <del> * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. <del> * <del> */ <del>function setCommandEcho(enabled) { <del> command_1.issue('echo', enabled ? 'on' : 'off'); <del>} <del>exports.setCommandEcho = setCommandEcho; <ide> //----------------------------------------------------------------------- <ide> // Results <ide> //----------------------------------------------------------------------- <ide> exports.debug = debug; <ide> /** <ide> * Adds an error issue <del> * @param message error issue message. Errors will be converted to string via toString() <add> * @param message error issue message <ide> */ <ide> function error(message) { <del> command_1.issue('error', message instanceof Error ? message.toString() : message); <add> command_1.issue('error', message); <ide> } <ide> exports.error = error; <ide> /** <ide> * Adds an warning issue <del> * @param message warning issue message. Errors will be converted to string via toString() <add> * @param message warning issue message <ide> */ <ide> function warning(message) { <del> command_1.issue('warning', message instanceof Error ? message.toString() : message); <add> command_1.issue('warning', message); <ide> } <ide> exports.warning = warning; <ide> /** <ide> * Saves state for current action, the state can only be retrieved by this action's post job execution. <ide> * <ide> * @param name name of the state to store <del> * @param value value to store. Non-string values will be converted to a string via JSON.stringify <add> * @param value value to store <ide> */ <del>// eslint-disable-next-line @typescript-eslint/no-explicit-any <ide> function saveState(name, value) { <ide> command_1.issueCommand('save-state', { name }, value); <ide> } <ide> /***/ }), <ide> <ide> /***/ 533: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_225477__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_216825__) { <ide> <ide> "use strict"; <ide> <ide> return (mod && mod.__esModule) ? mod : { "default": mod }; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const core = __importStar(__nested_webpack_require_225477__(470)); <del>const io = __importStar(__nested_webpack_require_225477__(1)); <del>const fs = __importStar(__nested_webpack_require_225477__(747)); <del>const mm = __importStar(__nested_webpack_require_225477__(31)); <del>const os = __importStar(__nested_webpack_require_225477__(87)); <del>const path = __importStar(__nested_webpack_require_225477__(622)); <del>const httpm = __importStar(__nested_webpack_require_225477__(539)); <del>const semver = __importStar(__nested_webpack_require_225477__(280)); <del>const stream = __importStar(__nested_webpack_require_225477__(794)); <del>const util = __importStar(__nested_webpack_require_225477__(669)); <del>const v4_1 = __importDefault(__nested_webpack_require_225477__(826)); <del>const exec_1 = __nested_webpack_require_225477__(986); <del>const assert_1 = __nested_webpack_require_225477__(357); <del>const retry_helper_1 = __nested_webpack_require_225477__(979); <add>const core = __importStar(__nested_webpack_require_216825__(470)); <add>const io = __importStar(__nested_webpack_require_216825__(1)); <add>const fs = __importStar(__nested_webpack_require_216825__(747)); <add>const os = __importStar(__nested_webpack_require_216825__(87)); <add>const path = __importStar(__nested_webpack_require_216825__(622)); <add>const httpm = __importStar(__nested_webpack_require_216825__(539)); <add>const semver = __importStar(__nested_webpack_require_216825__(280)); <add>const stream = __importStar(__nested_webpack_require_216825__(794)); <add>const util = __importStar(__nested_webpack_require_216825__(669)); <add>const v4_1 = __importDefault(__nested_webpack_require_216825__(826)); <add>const exec_1 = __nested_webpack_require_216825__(986); <add>const assert_1 = __nested_webpack_require_216825__(357); <add>const retry_helper_1 = __nested_webpack_require_216825__(979); <ide> class HTTPError extends Error { <ide> constructor(httpStatusCode) { <ide> super(`Unexpected HTTP response: ${httpStatusCode}`); <ide> * <ide> * @param url url of tool to download <ide> * @param dest path to download tool <del> * @param auth authorization header <ide> * @returns path to downloaded tool <ide> */ <del>function downloadTool(url, dest, auth) { <add>function downloadTool(url, dest) { <ide> return __awaiter(this, void 0, void 0, function* () { <ide> dest = dest || path.join(_getTempDirectory(), v4_1.default()); <ide> yield io.mkdirP(path.dirname(dest)); <ide> const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20); <ide> const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds); <ide> return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { <del> return yield downloadToolAttempt(url, dest || '', auth); <add> return yield downloadToolAttempt(url, dest || ''); <ide> }), (err) => { <ide> if (err instanceof HTTPError && err.httpStatusCode) { <ide> // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests <ide> }); <ide> } <ide> exports.downloadTool = downloadTool; <del>function downloadToolAttempt(url, dest, auth) { <add>function downloadToolAttempt(url, dest) { <ide> return __awaiter(this, void 0, void 0, function* () { <ide> if (fs.existsSync(dest)) { <ide> throw new Error(`Destination file path ${dest} already exists`); <ide> const http = new httpm.HttpClient(userAgent, [], { <ide> allowRetries: false <ide> }); <del> let headers; <del> if (auth) { <del> core.debug('set auth'); <del> headers = { <del> authorization: auth <del> }; <del> } <del> const response = yield http.get(url, headers); <add> const response = yield http.get(url); <ide> if (response.message.statusCode !== 200) { <ide> const err = new HTTPError(response.message.statusCode); <ide> core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`); <ide> process.chdir(dest); <ide> if (_7zPath) { <ide> try { <del> const logLevel = core.isDebug() ? '-bb1' : '-bb0'; <ide> const args = [ <ide> 'x', <del> logLevel, <add> '-bb1', <ide> '-bd', <ide> '-sccUTF-8', <ide> file <ide> core.debug(versionOutput.trim()); <ide> const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR'); <ide> // Initialize args <del> let args; <del> if (flags instanceof Array) { <del> args = flags; <del> } <del> else { <del> args = [flags]; <del> } <del> if (core.isDebug() && !flags.includes('v')) { <del> args.push('-v'); <del> } <add> const args = [flags]; <ide> let destArg = dest; <ide> let fileArg = file; <ide> if (IS_WINDOWS && isGnuTar) { <ide> const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); <ide> const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; <ide> // run powershell <del> const powershellPath = yield io.which('powershell', true); <add> const powershellPath = yield io.which('powershell'); <ide> const args = [ <ide> '-NoLogo', <ide> '-Sta', <ide> } <ide> function extractZipNix(file, dest) { <ide> return __awaiter(this, void 0, void 0, function* () { <del> const unzipPath = yield io.which('unzip', true); <del> const args = [file]; <del> if (!core.isDebug()) { <del> args.unshift('-q'); <del> } <del> yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest }); <add> const unzipPath = yield io.which('unzip'); <add> yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest }); <ide> }); <ide> } <ide> /** <ide> return versions; <ide> } <ide> exports.findAllVersions = findAllVersions; <del>function getManifestFromRepo(owner, repo, auth, branch = 'master') { <del> return __awaiter(this, void 0, void 0, function* () { <del> let releases = []; <del> const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`; <del> const http = new httpm.HttpClient('tool-cache'); <del> const headers = {}; <del> if (auth) { <del> core.debug('set auth'); <del> headers.authorization = auth; <del> } <del> const response = yield http.getJson(treeUrl, headers); <del> if (!response.result) { <del> return releases; <del> } <del> let manifestUrl = ''; <del> for (const item of response.result.tree) { <del> if (item.path === 'versions-manifest.json') { <del> manifestUrl = item.url; <del> break; <del> } <del> } <del> headers['accept'] = 'application/vnd.github.VERSION.raw'; <del> let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody(); <del> if (versionsRaw) { <del> // shouldn't be needed but protects against invalid json saved with BOM <del> versionsRaw = versionsRaw.replace(/^\uFEFF/, ''); <del> try { <del> releases = JSON.parse(versionsRaw); <del> } <del> catch (_a) { <del> core.debug('Invalid json'); <del> } <del> } <del> return releases; <del> }); <del>} <del>exports.getManifestFromRepo = getManifestFromRepo; <del>function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) { <del> return __awaiter(this, void 0, void 0, function* () { <del> // wrap the internal impl <del> const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter); <del> return match; <del> }); <del>} <del>exports.findFromManifest = findFromManifest; <ide> function _createExtractFolder(dest) { <ide> return __awaiter(this, void 0, void 0, function* () { <ide> if (!dest) { <ide> /***/ }), <ide> <ide> /***/ 539: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_247584__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_236540__) { <ide> <ide> "use strict"; <ide> <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const url = __nested_webpack_require_247584__(835); <del>const http = __nested_webpack_require_247584__(605); <del>const https = __nested_webpack_require_247584__(211); <del>const pm = __nested_webpack_require_247584__(950); <add>const url = __nested_webpack_require_236540__(835); <add>const http = __nested_webpack_require_236540__(605); <add>const https = __nested_webpack_require_236540__(211); <add>const pm = __nested_webpack_require_236540__(950); <ide> let tunnel; <ide> var HttpCodes; <ide> (function (HttpCodes) { <ide> if (useProxy) { <ide> // If using proxy, need tunnel <ide> if (!tunnel) { <del> tunnel = __nested_webpack_require_247584__(413); <add> tunnel = __nested_webpack_require_236540__(413); <ide> } <ide> const agentOptions = { <ide> maxSockets: maxSockets, <ide> /***/ }), <ide> <ide> /***/ 569: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_270274__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_259230__) { <ide> <ide> module.exports = rimraf <ide> rimraf.sync = rimrafSync <ide> <del>var assert = __nested_webpack_require_270274__(357) <del>var path = __nested_webpack_require_270274__(622) <del>var fs = __nested_webpack_require_270274__(747) <add>var assert = __nested_webpack_require_259230__(357) <add>var path = __nested_webpack_require_259230__(622) <add>var fs = __nested_webpack_require_259230__(747) <ide> var glob = undefined <ide> try { <del> glob = __nested_webpack_require_270274__(402) <add> glob = __nested_webpack_require_259230__(402) <ide> } catch (_err) { <ide> // treat glob as optional. <ide> } <ide> return [].concat(a, b); <ide> }; <ide> <del>var maybeMap = function maybeMap(val, fn) { <del> if (isArray(val)) { <del> var mapped = []; <del> for (var i = 0; i < val.length; i += 1) { <del> mapped.push(fn(val[i])); <del> } <del> return mapped; <del> } <del> return fn(val); <del>}; <del> <ide> module.exports = { <ide> arrayToObject: arrayToObject, <ide> assign: assign, <ide> encode: encode, <ide> isBuffer: isBuffer, <ide> isRegExp: isRegExp, <del> maybeMap: maybeMap, <ide> merge: merge <ide> }; <ide> <ide> /***/ }), <ide> <ide> /***/ 672: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_287959__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_276648__) { <ide> <ide> "use strict"; <ide> <ide> }; <ide> var _a; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const assert_1 = __nested_webpack_require_287959__(357); <del>const fs = __nested_webpack_require_287959__(747); <del>const path = __nested_webpack_require_287959__(622); <add>const assert_1 = __nested_webpack_require_276648__(357); <add>const fs = __nested_webpack_require_276648__(747); <add>const path = __nested_webpack_require_276648__(622); <ide> _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; <ide> exports.IS_WINDOWS = process.platform === 'win32'; <ide> function exists(fsPath) { <ide> /***/ }), <ide> <ide> /***/ 674: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_295636__) { <del> <del>var wrappy = __nested_webpack_require_295636__(11) <add>/***/ (function(module, __unusedexports, __nested_webpack_require_284325__) { <add> <add>var wrappy = __nested_webpack_require_284325__(11) <ide> var reqs = Object.create(null) <del>var once = __nested_webpack_require_295636__(49) <add>var once = __nested_webpack_require_284325__(49) <ide> <ide> module.exports = wrappy(inflight) <ide> <ide> /***/ }), <ide> <ide> /***/ 689: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_297767__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_286456__) { <ide> <ide> try { <del> var util = __nested_webpack_require_297767__(669); <add> var util = __nested_webpack_require_286456__(669); <ide> /* istanbul ignore next */ <ide> if (typeof util.inherits !== 'function') throw ''; <ide> module.exports = util.inherits; <ide> } catch (e) { <ide> /* istanbul ignore next */ <del> module.exports = __nested_webpack_require_297767__(315); <add> module.exports = __nested_webpack_require_286456__(315); <ide> } <ide> <ide> <ide> /***/ }), <ide> <ide> /***/ 729: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_298933__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_287622__) { <ide> <ide> "use strict"; <ide> <ide> }); <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const qs = __nested_webpack_require_298933__(386); <del>const url = __nested_webpack_require_298933__(835); <del>const path = __nested_webpack_require_298933__(622); <del>const zlib = __nested_webpack_require_298933__(761); <add>const qs = __nested_webpack_require_287622__(386); <add>const url = __nested_webpack_require_287622__(835); <add>const path = __nested_webpack_require_287622__(622); <add>const zlib = __nested_webpack_require_287622__(761); <ide> /** <ide> * creates an url from a request url and optional base url (http://server:8080) <ide> * @param {string} resource - a fully qualified url or relative path <ide> /***/ }), <ide> <ide> /***/ 755: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_304474__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_293163__) { <ide> <ide> "use strict"; <ide> <ide> <del>var utils = __nested_webpack_require_304474__(581); <add>var utils = __nested_webpack_require_293163__(581); <ide> <ide> var has = Object.prototype.hasOwnProperty; <ide> var isArray = Array.isArray; <ide> return val; <ide> }; <ide> <add>var maybeMap = function maybeMap(val, fn) { <add> if (isArray(val)) { <add> var mapped = []; <add> for (var i = 0; i < val.length; i += 1) { <add> mapped.push(fn(val[i])); <add> } <add> return mapped; <add> } <add> return fn(val); <add>}; <add> <ide> // This is what browsers will submit when the ✓ character occurs in an <ide> // application/x-www-form-urlencoded body and the encoding of the page containing <ide> // the form is iso-8859-1, or when the submitted form has an accept-charset <ide> val = options.strictNullHandling ? null : ''; <ide> } else { <ide> key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); <del> val = utils.maybeMap( <add> val = maybeMap( <ide> parseArrayValue(part.slice(pos + 1), options), <ide> function (encodedVal) { <ide> return options.decoder(encodedVal, defaults.decoder, charset, 'value'); <ide> /***/ }), <ide> <ide> /***/ 826: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_313931__) { <del> <del>var rng = __nested_webpack_require_313931__(139); <del>var bytesToUuid = __nested_webpack_require_313931__(722); <add>/***/ (function(module, __unusedexports, __nested_webpack_require_302857__) { <add> <add>var rng = __nested_webpack_require_302857__(139); <add>var bytesToUuid = __nested_webpack_require_302857__(722); <ide> <ide> function v4(options, buf, offset) { <ide> var i = buf && offset || 0; <ide> /***/ }), <ide> <ide> /***/ 856: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_314783__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_303709__) { <ide> <ide> exports.alphasort = alphasort <ide> exports.alphasorti = alphasorti <ide> return Object.prototype.hasOwnProperty.call(obj, field) <ide> } <ide> <del>var path = __nested_webpack_require_314783__(622) <del>var minimatch = __nested_webpack_require_314783__(93) <del>var isAbsolute = __nested_webpack_require_314783__(681) <add>var path = __nested_webpack_require_303709__(622) <add>var minimatch = __nested_webpack_require_303709__(93) <add>var isAbsolute = __nested_webpack_require_303709__(681) <ide> var Minimatch = minimatch.Minimatch <ide> <ide> function alphasorti (a, b) { <ide> /***/ }), <ide> <ide> /***/ 874: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_321048__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_309974__) { <ide> <ide> "use strict"; <ide> <ide> }); <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const url = __nested_webpack_require_321048__(835); <del>const http = __nested_webpack_require_321048__(605); <del>const https = __nested_webpack_require_321048__(211); <del>const util = __nested_webpack_require_321048__(729); <add>const url = __nested_webpack_require_309974__(835); <add>const http = __nested_webpack_require_309974__(605); <add>const https = __nested_webpack_require_309974__(211); <add>const util = __nested_webpack_require_309974__(729); <ide> let fs; <ide> let tunnel; <ide> var HttpCodes; <ide> this._certConfig = requestOptions.cert; <ide> if (this._certConfig) { <ide> // If using cert, need fs <del> fs = __nested_webpack_require_321048__(747); <add> fs = __nested_webpack_require_309974__(747); <ide> // cache the cert content into memory, so we don't have to read it from disk every time <ide> if (this._certConfig.caFile && fs.existsSync(this._certConfig.caFile)) { <ide> this._ca = fs.readFileSync(this._certConfig.caFile, 'utf8'); <ide> if (useProxy) { <ide> // If using proxy, need tunnel <ide> if (!tunnel) { <del> tunnel = __nested_webpack_require_321048__(413); <add> tunnel = __nested_webpack_require_309974__(413); <ide> } <ide> const agentOptions = { <ide> maxSockets: maxSockets, <ide> /***/ }), <ide> <ide> /***/ 897: <del>/***/ (function(module, __unusedexports, __nested_webpack_require_343891__) { <add>/***/ (function(module, __unusedexports, __nested_webpack_require_332817__) { <ide> <ide> "use strict"; <ide> <ide> <del>var utils = __nested_webpack_require_343891__(581); <del>var formats = __nested_webpack_require_343891__(13); <add>var utils = __nested_webpack_require_332817__(581); <add>var formats = __nested_webpack_require_332817__(13); <ide> var has = Object.prototype.hasOwnProperty; <ide> <ide> var arrayPrefixGenerators = { <ide> } else if (obj instanceof Date) { <ide> obj = serializeDate(obj); <ide> } else if (generateArrayPrefix === 'comma' && isArray(obj)) { <del> obj = utils.maybeMap(obj, function (value) { <del> if (value instanceof Date) { <del> return serializeDate(value); <del> } <del> return value; <del> }).join(','); <add> obj = obj.join(','); <ide> } <ide> <ide> if (obj === null) { <ide> <ide> for (var i = 0; i < objKeys.length; ++i) { <ide> var key = objKeys[i]; <del> var value = obj[key]; <del> <del> if (skipNulls && value === null) { <add> <add> if (skipNulls && obj[key] === null) { <ide> continue; <ide> } <ide> <del> var keyPrefix = isArray(obj) <del> ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix <del> : prefix + (allowDots ? '.' + key : '[' + key + ']'); <del> <del> pushToArray(values, stringify( <del> value, <del> keyPrefix, <del> generateArrayPrefix, <del> strictNullHandling, <del> skipNulls, <del> encoder, <del> filter, <del> sort, <del> allowDots, <del> serializeDate, <del> formatter, <del> encodeValuesOnly, <del> charset <del> )); <add> if (isArray(obj)) { <add> pushToArray(values, stringify( <add> obj[key], <add> typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, <add> generateArrayPrefix, <add> strictNullHandling, <add> skipNulls, <add> encoder, <add> filter, <add> sort, <add> allowDots, <add> serializeDate, <add> formatter, <add> encodeValuesOnly, <add> charset <add> )); <add> } else { <add> pushToArray(values, stringify( <add> obj[key], <add> prefix + (allowDots ? '.' + key : '[' + key + ']'), <add> generateArrayPrefix, <add> strictNullHandling, <add> skipNulls, <add> encoder, <add> filter, <add> sort, <add> allowDots, <add> serializeDate, <add> formatter, <add> encodeValuesOnly, <add> charset <add> )); <add> } <ide> } <ide> <ide> return values; <ide> /***/ }), <ide> <ide> /***/ 950: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_352018__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_341202__) { <ide> <ide> "use strict"; <ide> <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const url = __nested_webpack_require_352018__(835); <add>const url = __nested_webpack_require_341202__(835); <ide> function getProxyUrl(reqUrl) { <ide> let usingSsl = reqUrl.protocol === 'https:'; <ide> let proxyUrl; <ide> /***/ }), <ide> <ide> /***/ 962: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_353751__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_342935__) { <ide> <ide> "use strict"; <ide> <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); <del>}) : (function(o, m, k, k2) { <del> if (k2 === undefined) k2 = k; <del> o[k2] = m[k]; <del>})); <del>var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { <del> Object.defineProperty(o, "default", { enumerable: true, value: v }); <del>}) : function(o, v) { <del> o["default"] = v; <del>}); <del>var __importStar = (this && this.__importStar) || function (mod) { <del> if (mod && mod.__esModule) return mod; <del> var result = {}; <del> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); <del> __setModuleDefault(result, mod); <del> return result; <del>}; <ide> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { <ide> function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } <ide> return new (P || (P = Promise))(function (resolve, reject) { <ide> step((generator = generator.apply(thisArg, _arguments || [])).next()); <ide> }); <ide> }; <add>var __importStar = (this && this.__importStar) || function (mod) { <add> if (mod && mod.__esModule) return mod; <add> var result = {}; <add> if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; <add> result["default"] = mod; <add> return result; <add>}; <ide> var __importDefault = (this && this.__importDefault) || function (mod) { <ide> return (mod && mod.__esModule) ? mod : { "default": mod }; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>exports.installGcloudSDK = exports.GCLOUD_METRICS_LABEL = exports.GCLOUD_METRICS_ENV_VAR = void 0; <ide> /** <ide> * Contains installation utility functions. <ide> */ <del>const toolCache = __importStar(__nested_webpack_require_353751__(533)); <del>const core = __importStar(__nested_webpack_require_353751__(470)); <del>const path_1 = __importDefault(__nested_webpack_require_353751__(622)); <add>const toolCache = __importStar(__nested_webpack_require_342935__(533)); <add>const core = __importStar(__nested_webpack_require_342935__(470)); <add>const path_1 = __importDefault(__nested_webpack_require_342935__(622)); <ide> exports.GCLOUD_METRICS_ENV_VAR = 'CLOUDSDK_METRICS_ENVIRONMENT'; <ide> exports.GCLOUD_METRICS_LABEL = 'github-actions-setup-gcloud'; <ide> /** <ide> /***/ }), <ide> <ide> /***/ 979: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_357361__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_345898__) { <ide> <ide> "use strict"; <ide> <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const core = __importStar(__nested_webpack_require_357361__(470)); <add>const core = __importStar(__nested_webpack_require_345898__(470)); <ide> /** <ide> * Internal class for retries <ide> */ <ide> /***/ }), <ide> <ide> /***/ 986: <del>/***/ (function(__unusedmodule, exports, __nested_webpack_require_360288__) { <add>/***/ (function(__unusedmodule, exports, __nested_webpack_require_348825__) { <ide> <ide> "use strict"; <ide> <ide> return result; <ide> }; <ide> Object.defineProperty(exports, "__esModule", { value: true }); <del>const tr = __importStar(__nested_webpack_require_360288__(9)); <add>const tr = __importStar(__nested_webpack_require_348825__(9)); <ide> /** <ide> * Exec a command. <ide> * Output will be streamed to the live console.
JavaScript
mit
918bc398c7a9fc31a14ca1676af2639ac99edc78
0
follesoe/divemanager-edit,follesoe/divemanager-edit,follesoe/divemanager-edit
var fs = require('fs'); var express = require('express'); var cmp = require('semver-compare'); var app = express(); app.use(express.static('../../output')); app.get('/', function (req, res) { res.send('Squirrel Test Server'); }); app.get('/update/darwin_x64/:version', function (req, res) { var version = req.params.version; fs.readdir('../../output/SuuntoDMEditor-darwin-x64', function (err, files) { var zipFiles = files.filter(f => f.endsWith('.zip')).sort(cmp).reverse(); var match = /\d+\.\d+\.\d+/.exec(zipFiles[0]); if (match) { var latestVersion = match[0]; console.log('Checking for version newer than ' + version + ', found ' + latestVersion); if (cmp(latestVersion, version) == 1) { var url = req.protocol + '://' + req.get('host') + '/SuuntoDMEditor-darwin-x64/' + zipFiles[0]; var update = { url: url, name: latestVersion, notes: 'New ' + latestVersion + ' update with awesome new features!' }; res.send(update); } else { res.status(204).send(); } } }); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Squirrel Server listening at http://%s:%s', host, port); });
src/squirrel-server/app.js
var fs = require('fs'); var express = require('express'); var cmp = require('semver-compare'); var app = express(); app.use(express.static('../../output')); app.get('/', function (req, res) { res.send('Squirrel Test Server'); }); app.get('/update/darwin/:version', function (req, res) { var version = req.params.version; fs.readdir('../../output/SuuntoDMEditor-darwin-x64', function (err, files) { var zipFiles = files.filter(f => f.endsWith('.zip')).sort(cmp).reverse(); var match = /\d+\.\d+\.\d+/.exec(zipFiles[0]); if (match) { var latestVersion = match[0]; console.log('Checking for version newer than ' + version + ', found ' + latestVersion); if (cmp(latestVersion, version) == 1) { var url = req.protocol + '://' + req.get('host') + '/SuuntoDMEditor-darwin-x64/' + zipFiles[0]; var update = { url: url, name: latestVersion, notes: 'New ' + latestVersion + ' update with awesome new features!' }; res.send(update); } else { res.status(204).send(); } } }); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Squirrel Server listening at http://%s:%s', host, port); });
Add architecture to route
src/squirrel-server/app.js
Add architecture to route
<ide><path>rc/squirrel-server/app.js <ide> res.send('Squirrel Test Server'); <ide> }); <ide> <del>app.get('/update/darwin/:version', function (req, res) { <add>app.get('/update/darwin_x64/:version', function (req, res) { <ide> var version = req.params.version; <ide> fs.readdir('../../output/SuuntoDMEditor-darwin-x64', function (err, files) { <ide> var zipFiles = files.filter(f => f.endsWith('.zip')).sort(cmp).reverse();
Java
mit
error: pathspec 'tests/de/craften/craftenlauncher/logic/auth/MinecraftUserTest.java' did not match any file(s) known to git
ebf93bc6eb631d87ede1495abae67e2cbe570c04
1
TeamWertarbyte/craften-launcher
package de.craften.craftenlauncher.logic.auth; import org.junit.Test; import static org.junit.Assert.*; public class MinecraftUserTest { @Test public void testEquals() throws Exception { MinecraftUser user1 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); MinecraftUser user2 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); assertEquals(user1,user2); } @Test public void testNotEquals() throws Exception { MinecraftUser user1 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); MinecraftUser user2 = new MinecraftUser("[email protected]", "7m67mnb_profileid_kmmmnu","two","wj5wzw5_accesstoken_sdnmenb5","7mnmn5nbbnt_clienttoken_ws5mnza"); assertNotEquals(user1,user2); } }
tests/de/craften/craftenlauncher/logic/auth/MinecraftUserTest.java
Test for MinecraftUser equals Method
tests/de/craften/craftenlauncher/logic/auth/MinecraftUserTest.java
Test for MinecraftUser equals Method
<ide><path>ests/de/craften/craftenlauncher/logic/auth/MinecraftUserTest.java <add>package de.craften.craftenlauncher.logic.auth; <add> <add>import org.junit.Test; <add> <add>import static org.junit.Assert.*; <add> <add>public class MinecraftUserTest { <add> <add> @Test <add> public void testEquals() throws Exception { <add> MinecraftUser user1 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); <add> MinecraftUser user2 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); <add> <add> assertEquals(user1,user2); <add> } <add> <add> @Test <add> public void testNotEquals() throws Exception { <add> MinecraftUser user1 = new MinecraftUser("[email protected]", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb"); <add> MinecraftUser user2 = new MinecraftUser("[email protected]", "7m67mnb_profileid_kmmmnu","two","wj5wzw5_accesstoken_sdnmenb5","7mnmn5nbbnt_clienttoken_ws5mnza"); <add> <add> assertNotEquals(user1,user2); <add> } <add>}
JavaScript
mit
a322f50058f87d1a58e97cb6ef74b8fe2bababee
0
carlosalberto/echo-js,toshok/echojs,carlosalberto/echo-js,carlosalberto/echo-js,carlosalberto/echo-js,toshok/echojs,carlosalberto/echo-js,toshok/echojs,toshok/echojs,carlosalberto/echo-js,toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs
/* vim: set sw=4 ts=4 et tw=78: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Narcissus JavaScript engine. * * The Initial Developer of the Original Code is * Brendan Eich <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shu-Yu Guo <[email protected]> * Bruno Jouhier * Gregor Richards * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Narcissus - JS implemented in JS. * * Compiler to llvm assembly */ const lexer = require('./lexer'); const parser = require('./parser'); const definitions = require('./definitions'); const tyinfer = require('./typeinfer'); const tokens = definitions.tokens; // special key for parent scope when performing lookups const PARENT_SCOPE_KEY = ":parent:"; const EJS_CONTEXT_NAME = "__ejs_context"; const EJS_THIS_NAME = "__ejs_this"; const BUILTIN_ARGS = [ { name: EJS_CONTEXT_NAME, type: llvm.LLVMType.EjsValueType /* should be EjsContextType */ }, { name: EJS_THIS_NAME, type: llvm.LLVMType.EjsValueType } ]; // Set constants in the local scope. eval(definitions.consts); function isBlock(n) { return n && (n.type === BLOCK); } function isNonEmptyBlock(n) { return isBlock(n) && n.children.length > 0; } // marks an llvm function using its calling convention -- if ffi = true, we don't insert the 2 special ejs args into the call function ffi_c(func) { func.ffi = true; func.ffi_type = "C"; return func; } function ffi_objc(func) { func.ffi = true; func.ffi_type = "ObjC"; return func; } function NodeVisitor(module) { this.module = module; this.topScript = true; this.current_scope = {}; // build up our runtime method table this.ejs = { invoke_closure: [ ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_0", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type)), ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_1", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType)), ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_2", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_3", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)) ], number_new: ffi_c(module.getOrInsertExternalFunction("_ejs_number_new", llvm.LLVMType.EjsValueType, llvm.LLVMType.doubleType)), string_new_utf8: ffi_c(module.getOrInsertExternalFunction("_ejs_string_new_utf8", llvm.LLVMType.EjsValueType, llvm.LLVMType.stringType)), closure_new: ffi_c(module.getOrInsertExternalFunction("_ejs_closure_new", llvm.LLVMType.EjsFuncType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), print: ffi_c(module.getOrInsertExternalFunction("_ejs_print", llvm.LLVMType.voidType, llvm.LLVMType.EjsValueType)), op_add: ffi_c(module.getOrInsertExternalFunction("_ejs_op_add", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), op_sub: ffi_c(module.getOrInsertExternalFunction("_ejs_op_sub", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), op_or: ffi_c(module.getOrInsertExternalFunction("_ejs_op_or", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), op_strict_eq: ffi_c(module.getOrInsertExternalFunction("_ejs_op_strict_eq", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), truthy: ffi_c(module.getOrInsertExternalFunction("_ejs_truthy", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.boolType.pointerTo())), object_setprop: ffi_c(module.getOrInsertExternalFunction("_ejs_object_setprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), object_getprop: ffi_c(module.getOrInsertExternalFunction("_ejs_object_getprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())) }; } NodeVisitor.prototype.pushScope = function(new_scope) { new_scope[PARENT_SCOPE_KEY] = this.current_scope; this.current_scope = new_scope; }; NodeVisitor.prototype.popScope = function() { this.current_scope = this.current_scope[PARENT_SCOPE_KEY]; }; NodeVisitor.prototype.createAlloca = function (func, type, name) { let saved_insert_point = llvm.IRBuilder.getInsertBlock(); llvm.IRBuilder.setInsertPoint(func.entry_bb); let alloca = llvm.IRBuilder.createAlloca (type, name); llvm.IRBuilder.setInsertPoint(saved_insert_point); return alloca; }; NodeVisitor.prototype.createAllocas = function (func, names, scope) { let allocas = []; // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us let saved_insert_point = llvm.IRBuilder.getInsertBlock(); llvm.IRBuilder.setInsertPoint(func.entry_bb); for (let i = 0, j = names.length; i < j; i++) { let name = names[i].name; if (!scope[name]) { allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+name); scope[name] = allocas[i]; } } // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations llvm.IRBuilder.setInsertPoint (saved_insert_point); return allocas; }; NodeVisitor.prototype.visitScript = function(n,nc) { let top = this.topScript; this.topScript = false; let funcs = []; let nonfunc = []; for (let i = 0, j = nc.length; i < j; i++) { if (nc[i].type == FUNCTION) { funcs.push(nc[i]); } else { nonfunc.push(nc[i]); } } // generate the IR for all the functions first for (let i = 0, j = funcs.length; i < j; i++) { this.visit(funcs[i]); } let ir_func = top ? this.module.getOrInsertFunction("_ejs_script", BUILTIN_ARGS.length) : this.currentFunction; let ir_args = ir_func.getArgs(); if (top) { // XXX this block needs reworking to mirror what happens in visitFunction (particularly the distinction between entry/body_bb) this.currentFunction = ir_func; // Create a new basic block to start insertion into. var entry_bb = llvm.BasicBlock.create ("entry", ir_func); llvm.IRBuilder.setInsertPoint(entry_bb); ir_func.entry_bb = entry_bb; var new_scope = {}; ir_func.topScope = new_scope; this.current_scope = new_scope; let allocas = []; for (let i = 0, j = BUILTIN_ARGS.length; i < j; i++) { ir_args[i].setName(BUILTIN_ARGS[i].name); allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+BUILTIN_ARGS[i].name); new_scope[BUILTIN_ARGS[i].name] = allocas[i]; llvm.IRBuilder.createStore (ir_args[i], allocas[i]); } } for (let i = 0, j = nonfunc.length; i < j; i++) { var ir = this.visit(nonfunc[i]); } if (top) { // XXX this should be the actual return value for the script itself llvm.IRBuilder.createRet(llvm.Constant.getNull(llvm.LLVMType.EjsValueType)); } return ir_func; }; NodeVisitor.prototype.visitBlock = function(n,nc) { var new_scope = {}; this.pushScope(new_scope); let rv; for (let i = 0, j = nc.length; i < j; i++) { rv = this.visit(nc[i]); } this.popScope(); return rv; }; NodeVisitor.prototype.visitIf = function(n,nc) { // first we convert our conditional EJSValue to a boolean let truthy_stackalloc = this.createAlloca(this.currentFunction, llvm.LLVMType.boolType, "truthy_result"); llvm.IRBuilder.createCall(this.ejs.truthy, [this.visit(n.condition), truthy_stackalloc], "cond_truthy"); let cond_truthy = llvm.IRBuilder.createLoad(truthy_stackalloc, "truthy_load"); let insertBlock = llvm.IRBuilder.getInsertBlock(); let insertFunc = insertBlock.getParent(); var then_bb = llvm.BasicBlock.create ("then", insertFunc); var else_bb = llvm.BasicBlock.create ("else", insertFunc); var merge_bb = llvm.BasicBlock.create ("merge", insertFunc); // we invert the test here - check if the condition is false/0 let cmp = llvm.IRBuilder.createICmpEq (cond_truthy, llvm.Constant.getIntegerValue(llvm.LLVMType.boolType, 0), "cmpresult"); llvm.IRBuilder.createCondBr(cmp, else_bb, then_bb); llvm.IRBuilder.setInsertPoint(then_bb); let then_val = this.visit(n.thenPart); llvm.IRBuilder.createBr(merge_bb); llvm.IRBuilder.setInsertPoint(else_bb); let else_val = this.visit(n.elsePart); llvm.IRBuilder.setInsertPoint(merge_bb); return merge_bb; /* let pn = llvm.IRBuilder.createPhi(llvm.LLVMType.EjsValueType, 2, "iftmp"); pn.addIncoming (then_val, then_bb); pn.addIncoming (else_val, else_bb); return pn; */ }; NodeVisitor.prototype.visitReturn = function(n,nc) { return llvm.IRBuilder.createRet(this.visit(n.value)); }; NodeVisitor.prototype.visitVar = function(n,nc) { // vars are hoisted to the containing function's toplevel scope let scope = this.currentFunction.topScope; let allocas = this.createAllocas(this.currentFunction, nc, scope); for (let i = 0, j = nc.length; i < j; i++) { let initializer = this.visit(nc[i].initializer); let init_needs_closure = (initializer.toString() === "[object LLVMFunction]"); if (init_needs_closure) { initializer = llvm.IRBuilder.createCall(this.ejs.closure_new, [llvm.IRBuilder.createPointerCast(initializer, llvm.LLVMType.EjsFuncType, "castfunc"), llvm.Constant.getNull(llvm.LLVMType.EjsValueType)/*XXX*/], "closure"); } llvm.IRBuilder.createStore (initializer, allocas[i]); } }; NodeVisitor.prototype.visitLet = function(n,nc) { // lets are not hoisted to the containing function's toplevel, but instead are bound in the lexical block they inhabit let scope = this.current_scope; let allocas = this.createAllocas(this.currentFunction, nc, scope); for (let i = 0, j = nc.length; i < j; i++) { llvm.IRBuilder.createStore (this.visit(nc[i].initializer), allocas[i]); } }; NodeVisitor.prototype.visitConst = function(n,nc) { for (let i = 0, j = nc.length; i < j; i++) { var u = nc[i]; var initializer_ir = this.visit (u.initializer); // XXX bind the initializer to u.name in the current basic block and mark it as constant } }; NodeVisitor.prototype.createPropertyStore = function(obj,propname,rhs) { // we assume propname is a string/identifier here... let pname = this.visitString(propname); return llvm.IRBuilder.createCall(this.ejs.object_setprop, [this.visit(obj), pname, rhs], "propstore_"+propname.value); }; NodeVisitor.prototype.createPropertyLoad = function(obj,propname) { // we assume propname is a string/identifier here... let pname = this.visitString(propname); let result = this.createAlloca(llvm.LLVMType.EjsValueType, "result"); let rv = llvm.IRBuilder.createCall(this.ejs.object_getprop, [this.visit(obj), pname, result], "propload_"+propname.value); return llvm.IRBuilder.createLoad(result, "result_propload"); }; NodeVisitor.prototype.visitAssign = function(n,nc) { var lhs = nc[0]; var rhs = nc[1]; if (lhs.type == IDENTIFIER) { return llvm.IRBuilder.createStore (this.visit(rhs), findIdentifierInScope(lhs.value, this.current_scope)); } else if (lhs.type == DOT) { print ("creating propertystore!"); rhs = this.visit(rhs); let rhs_needs_closure = (rhs.toString() === "[object LLVMFunction]"); if (rhs_needs_closure) { print ("creating closure"); rhs = llvm.IRBuilder.createCall(this.ejs.closure_new, [llvm.IRBuilder.createPointerCast(rhs, llvm.LLVMType.EjsFuncType, "castfunc"), llvm.Constant.getNull(llvm.LLVMType.EjsValueType)/*XXX*/], "closure"); print ("done creating closure"); } return this.createPropertyStore (lhs.children[0], lhs.children[1], rhs); } else { throw "unhandled assign lhs"; } }; NodeVisitor.prototype.visitFunction = function(n,nc) { // save off the insert point so we can get back to it after generating this function let insertBlock = llvm.IRBuilder.getInsertBlock(); for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) !== 'string') { print ("we don't handle destructured/defaulted parameters yet"); throw "we don't handle destructured/defaulted parameters yet"; } } // XXX this methods needs to be augmented so that we can pass actual types (or the builtin args need // to be reflected in jsllvm.cpp too). maybe we can pass the names to this method and it can do it all // there? print ("visitFunction, 1"); for (let i = BUILTIN_ARGS.length - 1, j = 0; i >= j; i--) { n.params.unshift(BUILTIN_ARGS[i].name); } if (!n.name || n.name == "") n.name = "_ejs_anonymous"; var ir_func = this.module.getOrInsertFunction (n.name, n.params.length); this.currentFunction = ir_func; var ir_args = ir_func.getArgs(); for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) === 'string') { ir_args[i].setName(n.params[i]); } else { ir_args[i].setName("__ejs_destructured_param"); } } print ("visitFunction, 4"); // Create a new basic block to start insertion into. var entry_bb = llvm.BasicBlock.create ("entry", ir_func); llvm.IRBuilder.setInsertPoint(entry_bb); var new_scope = {}; // we save off the top scope and entry_bb of the function so that we can hoist vars there ir_func.topScope = new_scope; ir_func.entry_bb = entry_bb; let allocas = []; // store the arguments on the stack for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) === 'string') { allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+n.params[i]); } else { print ("we don't handle destructured args at the moment."); throw "we don't handle destructured args at the moment."; } } for (let i = 0, j = n.params.length; i < j; i++) { // store the allocas in the scope we're going to push onto the scope stack new_scope[n.params[i]] = allocas[i]; llvm.IRBuilder.createStore (ir_args[i], allocas[i]); } var body_bb = llvm.BasicBlock.create ("body", ir_func); llvm.IRBuilder.setInsertPoint(body_bb); this.pushScope(new_scope); this.visit(n.body); this.popScope(); // XXX more needed here - this lacks all sorts of control flow stuff. // Finish off the function. llvm.IRBuilder.createRet(llvm.Constant.getNull(llvm.LLVMType.EjsValueType)); // insert an unconditional branch from entry_bb to body here, now that we're // sure we're not going to be inserting allocas into the entry_bb anymore. llvm.IRBuilder.setInsertPoint(entry_bb); llvm.IRBuilder.createBr(body_bb); this.currentFunction = null; print ("returning function"); llvm.IRBuilder.setInsertPoint(insertBlock); return ir_func; }; NodeVisitor.prototype.visitSemicolon = function(n,nc) { return this.visit(n.expression); }; NodeVisitor.prototype.visitList = function(n,nc) { return nc; }; NodeVisitor.prototype.visitBinOp = function(n,nc,builtin) { let callee = this.module.getFunction(builtin); // allocate space on the stack for the result let result = this.createAlloca(this.currentFunction, llvm.LLVMType.EjsValueType, "result_" + builtin); // call the add method let rv = llvm.IRBuilder.createCall(callee, [this.visit(nc[0]), this.visit(nc[1]), result], "result"); // load and return the result return llvm.IRBuilder.createLoad(result, "result_"+builtin+"_load"); }; NodeVisitor.prototype.createLoadThis = function () { let _this = this.current_scope[EJS_THIS_NAME]; return llvm.IRBuilder.createLoad (this.current_scope[EJS_THIS_NAME], "load_this"); }; NodeVisitor.prototype.createLoadContext = function () { if (!this.current_scope[EJS_CONTEXT_NAME]) print ("die die die"); return llvm.IRBuilder.createLoad (this.current_scope[EJS_CONTEXT_NAME], "load_context"); }; NodeVisitor.prototype.visitCall = function(n,nc) { print ("visitCall " + nc[0]); let callee = this.visit (nc[0]); let args = this.visit (nc[1]); if (callee.type && callee.type == DOT) { print ("creating property load!"); callee = this.createPropertyLoad (callee.children[0], callee.children[1]); } // XXX this needs to be a better instanceof check let callee_is_closure = (callee.toString() !== "[object LLVMFunction]"); // At this point we assume callee is a function object let compiled_arg_start; if (callee_is_closure) { print ("loading closure args"); compiled_arg_start = 3; // closure invokers take the EJSContext and an arg length args.unshift(llvm.Constant.getIntegerValue(llvm.LLVMType.int32Type, args.length)); args.unshift(callee); args.unshift(this.createLoadContext()); } else if (!callee.ffi) { print ("loading this and context"); // we insert the extra BUILTIN_ARGS since we're calling a JS function args.unshift(this.createLoadThis()); args.unshift(this.createLoadContext()); compiled_arg_start = 2; print ("done loading this and context"); } else { print ("ffi function, not loading this and context"); compiled_arg_start = 0; } print ("callee = " + callee.toString()); let argv = []; for (let i = 0, j = args.length; i < j; i++) { if (i < compiled_arg_start) argv[i] = args[i]; else argv[i] = this.visit(args[i]); } if (callee_is_closure) { print (1); let invoke_fun = this.ejs.invoke_closure[argv.length-compiled_arg_start]; print ("2 invoke_fun = this.ejs.invoke_closure[" + (argv.length-compiled_arg_start) + "]"); let rv = llvm.IRBuilder.createCall(invoke_fun, argv, "calltmp"); print (3); return rv; } else { // we're dealing with a function here if (callee.argSize() !== args.length) { // this isn't invalid in JS. if argSize > args.length, the args are undefined. // if argSize < args.length, the args are still passed } return llvm.IRBuilder.createCall(callee, argv, callee.returnType().isVoid() ? "" : "calltmp"); } }; NodeVisitor.prototype.visitNew = function(n,nc) { let ctor = this.visit (nc[0]); let args = this.visit (nc[1]); // At this point we assume callee is a function object if (callee.argSize() !== args.length) { // this isn't invalid in JS. if argSize > args.length, the args are undefined. // if argSize < args.length, the args are still passed } let argv = []; for (let i = 0, j = args.length; i < j; i++) { argv[i] = this.visit(args[i]); } let rv = llvm.IRBuilder.createCall(callee, argv, "newtmp"); return rv; }; NodeVisitor.prototype.visitPropertyAccess = function(n,nc) { print ("property access: " + nc[1].value); return n; }; NodeVisitor.prototype.visitThis = function(n, nc) { print ("visitThis"); return this.createLoadThis(); }; function findIdentifierInScope (ident, scope) { while (scope) { if (scope[ident]) return scope[ident]; scope = scope[PARENT_SCOPE_KEY]; } return null; } NodeVisitor.prototype.visitIdentifier = function(n,nc) { let val = n.value; var alloca = findIdentifierInScope (val, this.current_scope); if (alloca) { return llvm.IRBuilder.createLoad(alloca, "load_"+val); } let func = null; // we should probably insert a global scope at the toplevel (above the actual user-level global scope) that includes all these renamings/functions? if (val == "print") { func = this.ejs.print; } else { func = this.module.getFunction(val); } if (func) return func; throw "Symbol '" + val + "' not found in current scope"; }; NodeVisitor.prototype.visitNumber = function(n,nc) { let c = llvm.ConstantFP.getDouble(n.value); let call = llvm.IRBuilder.createCall(this.ejs.number_new, [c], "numtmp"); return call; }; NodeVisitor.prototype.visitString = function(n,nc) { print ("visitString"); let c = llvm.IRBuilder.createGlobalStringPtr(n.value, "strconst"); let call = llvm.IRBuilder.createCall(this.ejs.string_new_utf8, [c], "strtmp"); return call; }; NodeVisitor.prototype.visit = function(n) { if (!n) return n; //print (tokens[n.type]); let nc = n.children; switch (n.type) { case FUNCTION: return this.visitFunction(n,nc); case GETTER: return this.visitGetter(n,nc); case SETTER: return this.visitSetter(n,nc); case SCRIPT: return this.visitScript(n,nc); case BLOCK: return this.visitBlock(n,nc); case LET_BLOCK: return this.visitBlock(n,nc); case SWITCH: return this.visitSwitch(n,nc); case FOR: return this.visitFor(n,nc); case WHILE: return this.visitWhile(n,nc); case IF: return this.visitIf(n,nc); case FOR_IN: return this.visitForIn(n,nc); case DO: return this.visitDo(n,nc); case BREAK: return this.visitBreak(n,nc); case CONTINUE: return this.visitContinue(n,nc); case TRY: return this.visitTry(n,nc); case THROW: return this.visitThrow(n,nc); case RETURN: return this.visitReturn(n,nc); case YIELD: return this.visitYield(n,nc); case GENERATOR: return this.visitGenerator(n,nc); case WITH: return this.visitWith(n,nc); case LET: return this.visitLet(n,nc); case VAR: return this.visitVar(n,nc); case CONST: return this.visitConst(n,nc); case DEBUGGER: return this.visitDebugger(n,nc); case SEMICOLON: return this.visitSemicolon(n,nc); case LABEL: return this.visitLabel(n,nc); case COMMA: return this.visitComma(n,nc); case LIST: return this.visitList(n,nc); case ASSIGN: return this.visitAssign(n,nc); case HOOK: return this.visitHook(n,nc); case OR: return this.visitBinOp(n,nc,"_ejs_op_or"); case AND: return this.visitAnd(n,nc); case BITWISE_OR: return this.visitBitwiseOr(n,nc); case BITWISE_XOR: return this.visitBitwiseXor(n,nc); case BITWISE_AND: return this.visitBitwiseAnd(n,nc); case EQ: return this.visitEq(n,nc); case NE: return this.visitNe(n,nc); case STRICT_EQ: return this.visitBinOp(n,nc,"_ejs_op_strict_eq"); case STRICT_NE: return this.visitStrictNe(n,nc); case LT: return this.visitLT(n,nc); case LE: return this.visitLE(n,nc); case GE: return this.visitGE(n,nc); case GT: return this.visitGT(n,nc); case IN: return this.visitIN(n,nc); case INSTANCEOF: return this.visitInstanceOf(n,nc); case LSH: return this.visitLSH(n,nc); case RSH: return this.visitRSH(n,nc); case URSH: return this.visitURSH(n,nc); case PLUS: return this.visitBinOp(n,nc,"_ejs_op_add"); case MINUS: return this.visitBinOp(n,nc,"_ejs_op_sub"); case IDENTIFIER: return this.visitIdentifier(n,nc); case NUMBER: return this.visitNumber(n,nc); case STRING: return this.visitString(n,nc); case CALL: return this.visitCall(n,nc); case NEW: return this.visitNew(n,nc); case MUL: case DIV: case MOD: case DELETE: case VOID: case TYPEOF: case NOT: case BITWISE_NOT: case UNARY_PLUS: case UNARY_MINUS: case INCREMENT: case DECREMENT: case DOT: return this.visitPropertyAccess(n,nc); case INDEX: break; case NEW_WITH_ARGS: case ARRAY_INIT: case ARRAY_COMP: case COMP_TAIL: case OBJECT_INIT: case NULL: case THIS: return this.visitThis(n,nc); case TRUE: case FALSE: case REGEXP: case GROUP: default: throw "PANIC: unknown operation " + tokens[n.type] + " " + n.toSource(); } }; function compile(n,nc) { /* var infer = new tyinfer.TypeInfer(n); infer.run (); */ var module = new llvm.LLVMModule("compiledfoo"); var visitor = new NodeVisitor(module); var ir = visitor.visit(n); module.dump(); quit(0); } exports.compile = compile;
lib/compiler.js
/* vim: set sw=4 ts=4 et tw=78: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Narcissus JavaScript engine. * * The Initial Developer of the Original Code is * Brendan Eich <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shu-Yu Guo <[email protected]> * Bruno Jouhier * Gregor Richards * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Narcissus - JS implemented in JS. * * Compiler to llvm assembly */ const lexer = require('./lexer'); const parser = require('./parser'); const definitions = require('./definitions'); const tyinfer = require('./typeinfer'); const tokens = definitions.tokens; // special key for parent scope when performing lookups const PARENT_SCOPE_KEY = ":parent:"; // Set constants in the local scope. eval(definitions.consts); function isBlock(n) { return n && (n.type === BLOCK); } function isNonEmptyBlock(n) { return isBlock(n) && n.children.length > 0; } function NodeVisitor(module) { this.module = module; this.topScript = true; this.current_scope = {}; this.ejs_number_new = module.getOrInsertExternalFunction("_ejs_number_new", llvm.LLVMType.EjsValueType, llvm.LLVMType.doubleType); this.ejs_string_new_utf8 = module.getOrInsertExternalFunction("_ejs_string_new_utf8", llvm.LLVMType.EjsValueType, llvm.LLVMType.stringType); this.ejs_print = module.getOrInsertExternalFunction("_ejs_print", llvm.LLVMType.voidType, llvm.LLVMType.EjsValueType); this.ejs_op_add = module.getOrInsertExternalFunction("_ejs_op_add", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); this.ejs_op_sub = module.getOrInsertExternalFunction("_ejs_op_sub", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); this.ejs_op_or = module.getOrInsertExternalFunction("_ejs_op_or", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); this.ejs_op_strict_eq = module.getOrInsertExternalFunction("_ejs_op_strict_eq", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); this.ejs_truthy = module.getOrInsertExternalFunction("_ejs_truthy", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.boolType.pointerTo()); this.ejs_object_setprop = module.getOrInsertExternalFunction("_ejs_object_setprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType); this.ejs_object_getprop = module.getOrInsertExternalFunction("_ejs_object_getprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); } NodeVisitor.prototype.pushScope = function(new_scope) { new_scope[PARENT_SCOPE_KEY] = this.current_scope; this.current_scope = new_scope; }; NodeVisitor.prototype.popScope = function() { this.current_scope = this.current_scope[PARENT_SCOPE_KEY]; }; NodeVisitor.prototype.visitScript = function(n,nc) { let top = this.topScript; this.topScript = false; let funcs = []; let nonfunc = []; for (let i = 0, j = nc.length; i < j; i++) { if (nc[i].type == FUNCTION) { funcs.push(nc[i]); } else { nonfunc.push(nc[i]); } } // generate the IR for all the functions first for (let i = 0, j = funcs.length; i < j; i++) { this.visit(funcs[i]); } var ir_func = top ? this.module.getOrInsertFunction("_ejs_script", 0) : this.currentFunction; if (top) { // XXX this block needs reworking to mirror what happens in visitFunction (particularly the distinction between entry/body_bb) this.currentFunction = ir_func; // Create a new basic block to start insertion into. var entry_bb = llvm.BasicBlock.create ("entry", ir_func); llvm.IRBuilder.setInsertPoint(entry_bb); ir_func.entry_bb = entry_bb; var scope = {}; ir_func.topScope = scope; this.current_scope = scope; } for (let i = 0, j = nonfunc.length; i < j; i++) { var ir = this.visit(nonfunc[i]); } if (top) { // XXX this should be the actual return value for the script itself llvm.IRBuilder.createRet(llvm.Constant.getNull(llvm.LLVMType.EjsValueType)); } return ir_func; }; NodeVisitor.prototype.visitBlock = function(n,nc) { var new_scope = {}; this.pushScope(new_scope); let rv; for (let i = 0, j = nc.length; i < j; i++) { rv = this.visit(nc[i]); } this.popScope(); return rv; }; NodeVisitor.prototype.visitIf = function(n,nc) { // first we convert our conditional EJSValue to a boolean let get_truthy = this.module.getFunction("_ejs_truthy"); let truthy_stackalloc = llvm.IRBuilder.createAlloca(llvm.LLVMType.boolType, "truthy_result"); llvm.IRBuilder.createCall(get_truthy, [this.visit(n.condition), truthy_stackalloc], "cond_truthy"); let cond_truthy = llvm.IRBuilder.createLoad(truthy_stackalloc, "truthy_load"); let insertBlock = llvm.IRBuilder.getInsertBlock(); let insertFunc = insertBlock.getParent(); var then_bb = llvm.BasicBlock.create ("then", insertFunc); var else_bb = llvm.BasicBlock.create ("else", insertFunc); var merge_bb = llvm.BasicBlock.create ("merge", insertFunc); // we invert the test here - check if the condition is false/0 let cmp = llvm.IRBuilder.createICmpEq (cond_truthy, llvm.Constant.getIntegerValue(llvm.LLVMType.boolType, 0), "cmpresult"); llvm.IRBuilder.createCondBr(cmp, else_bb, then_bb); llvm.IRBuilder.setInsertPoint(then_bb); let then_val = this.visit(n.thenPart); llvm.IRBuilder.createBr(merge_bb); llvm.IRBuilder.setInsertPoint(else_bb); let else_val = this.visit(n.elsePart); llvm.IRBuilder.setInsertPoint(merge_bb); return merge_bb; /* let pn = llvm.IRBuilder.createPhi(llvm.LLVMType.EjsValueType, 2, "iftmp"); pn.addIncoming (then_val, then_bb); pn.addIncoming (else_val, else_bb); return pn; */ }; NodeVisitor.prototype.visitReturn = function(n,nc) { return llvm.IRBuilder.createRet(this.visit(n.value)); }; NodeVisitor.prototype.createAllocasForDecls = function (n,nc,scope) { let allocas = []; for (let i = 0, j = nc.length; i < j; i++) { let name = nc[i].name; if (!scope[name]) { allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+name); scope[name] = allocas[i]; } } return allocas; }; NodeVisitor.prototype.visitVar = function(n,nc) { // vars are hoisted to the containing function's toplevel scope let scope = this.currentFunction.topScope; // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us let insertBlock = llvm.IRBuilder.getInsertBlock(); llvm.IRBuilder.setInsertPoint(this.currentFunction.entry_bb); let allocas = this.createAllocasForDecls(n, nc, scope); // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations llvm.IRBuilder.setInsertPoint (insertBlock); for (let i = 0, j = nc.length; i < j; i++) { llvm.IRBuilder.createStore (this.visit(nc[i].initializer), allocas[i]); } }; NodeVisitor.prototype.visitLet = function(n,nc) { // lets are not hoisted to the containing function's toplevel, but instead are bound in the lexical block they inhabit let scope = this.current_scope; // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us let insertBlock = llvm.IRBuilder.getInsertBlock(); llvm.IRBuilder.setInsertPoint(this.currentFunction.entry_bb); let allocas = this.createAllocasForDecls(n, nc, scope); // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations llvm.IRBuilder.setInsertPoint (insertBlock); for (let i = 0, j = nc.length; i < j; i++) { llvm.IRBuilder.createStore (this.visit(nc[i].initializer), allocas[i]); } }; NodeVisitor.prototype.visitConst = function(n,nc) { for (let i = 0, j = nc.length; i < j; i++) { var u = nc[i]; var initializer_ir = this.visit (u.initializer); // XXX bind the initializer to u.name in the current basic block and mark it as constant } }; NodeVisitor.prototype.visitAssign = function(n,nc) { var lhs = nc[0]; var rhs = nc[1]; print (lhs); if (lhs.type == IDENTIFIER) { llvm.IRBuilder.createStore (this.visit(rhs), findIdentifierInScope(lhs.value, this.current_scope)); } else { throw "unhandled assign lhs"; } }; NodeVisitor.prototype.visitFunction = function(n,nc) { for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) !== 'string') { print ("we don't handle destructured/defaulted parameters yet"); throw "we don't handle destructured/defaulted parameters yet"; } } var ir_func = this.module.getOrInsertFunction (n.name, n.params.length); this.currentFunction = ir_func; var ir_args = ir_func.getArgs(); for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) === 'string') { ir_args[i].setName(n.params[i]); } else { ir_args[i].setName("__ejs_destructured_param"); } } // Create a new basic block to start insertion into. var entry_bb = llvm.BasicBlock.create ("entry", ir_func); llvm.IRBuilder.setInsertPoint(entry_bb); var new_scope = {}; // we save off the top scope and entry_bb of the function so that we can hoist vars there ir_func.topScope = new_scope; ir_func.entry_bb = entry_bb; let allocas = []; // store the arguments on the stack for (let i = 0, j = n.params.length; i < j; i++) { if (typeof (n.params[i]) === 'string') { allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+n.params[i]); } else { print ("we don't handle destructured args at the moment."); throw "we don't handle destructured args at the moment."; } } for (let i = 0, j = n.params.length; i < j; i++) { // store the allocas in the scope we're going to push onto the scope stack new_scope[n.params[i]] = allocas[i]; llvm.IRBuilder.createStore (ir_args[i], allocas[i]); } var body_bb = llvm.BasicBlock.create ("body", ir_func); llvm.IRBuilder.setInsertPoint(body_bb); this.pushScope(new_scope); this.visit(n.body); this.popScope(); // XXX more needed here - this lacks all sorts of control flow stuff. // Finish off the function. llvm.IRBuilder.createRet(llvm.Constant.getNull(llvm.LLVMType.EjsValueType)); // insert an unconditional branch from entry_bb to body here, now that we're // sure we're not going to be inserting allocas into the entry_bb anymore. llvm.IRBuilder.setInsertPoint(entry_bb); llvm.IRBuilder.createBr(body_bb); this.currentFunction = null; return ir_func; }; NodeVisitor.prototype.visitSemicolon = function(n,nc) { return this.visit(n.expression); }; NodeVisitor.prototype.visitList = function(n,nc) { return nc; }; NodeVisitor.prototype.visitBinOp = function(n,nc,builtin) { let callee = this.module.getFunction(builtin); // allocate space on the stack for the result let result = llvm.IRBuilder.createAlloca(llvm.LLVMType.EjsValueType, "result_" + builtin); // call the add method let rv = llvm.IRBuilder.createCall(callee, [this.visit(nc[0]), this.visit(nc[1]), result], "result"); // load and return the result return llvm.IRBuilder.createLoad(result, "result_"+builtin+"_load"); }; NodeVisitor.prototype.visitCall = function(n,nc) { let callee = this.visit (nc[0]); let args = this.visit (nc[1]); // At this point we assume callee is a function object if (callee.argSize() !== args.length) { // this isn't invalid in JS. if argSize > args.length, the args are undefined. // if argSize < args.length, the args are still passed } let argv = []; for (let i = 0, j = args.length; i < j; i++) { argv[i] = this.visit(args[i]); } let rv = llvm.IRBuilder.createCall(callee, argv, callee.returnType().isVoid() ? "" : "calltmp"); return rv; }; NodeVisitor.prototype.visitNew = function(n,nc) { let ctor = this.visit (nc[0]); let args = this.visit (nc[1]); // At this point we assume callee is a function object if (callee.argSize() !== args.length) { // this isn't invalid in JS. if argSize > args.length, the args are undefined. // if argSize < args.length, the args are still passed } let argv = []; for (let i = 0, j = args.length; i < j; i++) { argv[i] = this.visit(args[i]); } let rv = llvm.IRBuilder.createCall(callee, argv, "newtmp"); return rv; }; function findIdentifierInScope (ident, scope) { while (scope) { if (scope[ident]) return scope[ident]; scope = scope[PARENT_SCOPE_KEY]; } return null; } NodeVisitor.prototype.visitIdentifier = function(n,nc) { let val = n.value; var alloca = findIdentifierInScope (val, this.current_scope); if (alloca) { return llvm.IRBuilder.createLoad(alloca, "load_"+val); } // we should probably insert a global scope at the toplevel (above the actual user-level global scope) that includes all these renamings/functions? if (val == "print") val = "_ejs_print"; var func = this.module.getFunction(val); if (func) return func; throw "Symbol '" + val + "' not found in current scope"; }; NodeVisitor.prototype.visitNumber = function(n,nc) { let c = llvm.ConstantFP.getDouble(n.value); let call = llvm.IRBuilder.createCall(this.ejs_number_new, [c], "numtmp"); return call; }; NodeVisitor.prototype.visitString = function(n,nc) { let c = llvm.IRBuilder.createGlobalStringPtr(n.value, "strconst"); let call = llvm.IRBuilder.createCall(this.ejs_string_new_utf8, [c], "strtmp"); return call; }; NodeVisitor.prototype.visit = function(n) { if (!n) return n; //print (tokens[n.type]); let nc = n.children; switch (n.type) { case FUNCTION: return this.visitFunction(n,nc); case GETTER: return this.visitGetter(n,nc); case SETTER: return this.visitSetter(n,nc); case SCRIPT: return this.visitScript(n,nc); case BLOCK: return this.visitBlock(n,nc); case LET_BLOCK: return this.visitBlock(n,nc); case SWITCH: return this.visitSwitch(n,nc); case FOR: return this.visitFor(n,nc); case WHILE: return this.visitWhile(n,nc); case IF: return this.visitIf(n,nc); case FOR_IN: return this.visitForIn(n,nc); case DO: return this.visitDo(n,nc); case BREAK: return this.visitBreak(n,nc); case CONTINUE: return this.visitContinue(n,nc); case TRY: return this.visitTry(n,nc); case THROW: return this.visitThrow(n,nc); case RETURN: return this.visitReturn(n,nc); case YIELD: return this.visitYield(n,nc); case GENERATOR: return this.visitGenerator(n,nc); case WITH: return this.visitWith(n,nc); case LET: return this.visitLet(n,nc); case VAR: return this.visitVar(n,nc); case CONST: return this.visitConst(n,nc); case DEBUGGER: return this.visitDebugger(n,nc); case SEMICOLON: return this.visitSemicolon(n,nc); case LABEL: return this.visitLabel(n,nc); case COMMA: return this.visitComma(n,nc); case LIST: return this.visitList(n,nc); case ASSIGN: return this.visitAssign(n,nc); case HOOK: return this.visitHook(n,nc); case OR: return this.visitBinOp(n,nc,"_ejs_op_or"); case AND: return this.visitAnd(n,nc); case BITWISE_OR: return this.visitBitwiseOr(n,nc); case BITWISE_XOR: return this.visitBitwiseXor(n,nc); case BITWISE_AND: return this.visitBitwiseAnd(n,nc); case EQ: return this.visitEq(n,nc); case NE: return this.visitNe(n,nc); case STRICT_EQ: return this.visitBinOp(n,nc,"_ejs_op_strict_eq"); case STRICT_NE: return this.visitStrictNe(n,nc); case LT: return this.visitLT(n,nc); case LE: return this.visitLE(n,nc); case GE: return this.visitGE(n,nc); case GT: return this.visitGT(n,nc); case IN: return this.visitIN(n,nc); case INSTANCEOF: return this.visitInstanceOf(n,nc); case LSH: return this.visitLSH(n,nc); case RSH: return this.visitRSH(n,nc); case URSH: return this.visitURSH(n,nc); case PLUS: return this.visitBinOp(n,nc,"_ejs_op_add"); case MINUS: return this.visitBinOp(n,nc,"_ejs_op_sub"); case IDENTIFIER: return this.visitIdentifier(n,nc); case NUMBER: return this.visitNumber(n,nc); case STRING: return this.visitString(n,nc); case CALL: return this.visitCall(n,nc); case NEW: return this.visitNew(n,nc); case MUL: case DIV: case MOD: case DELETE: case VOID: case TYPEOF: case NOT: case BITWISE_NOT: case UNARY_PLUS: case UNARY_MINUS: case INCREMENT: case DECREMENT: case DOT: print ("DOT"); break; case INDEX: break; case NEW_WITH_ARGS: case ARRAY_INIT: case ARRAY_COMP: case COMP_TAIL: case OBJECT_INIT: case NULL: case THIS: print ("THIS"); break; case TRUE: case FALSE: case REGEXP: case GROUP: default: throw "PANIC: unknown operation " + tokens[n.type] + " " + n.toSource(); } }; function compile(n,nc) { /* var infer = new tyinfer.TypeInfer(n); infer.run (); */ var module = new llvm.LLVMModule("compiledfoo"); var visitor = new NodeVisitor(module); var ir = visitor.visit(n); module.dump(); quit(0); } exports.compile = compile;
lots of misc updates
lib/compiler.js
lots of misc updates
<ide><path>ib/compiler.js <ide> // special key for parent scope when performing lookups <ide> const PARENT_SCOPE_KEY = ":parent:"; <ide> <add>const EJS_CONTEXT_NAME = "__ejs_context"; <add>const EJS_THIS_NAME = "__ejs_this"; <add> <add>const BUILTIN_ARGS = [ <add> { name: EJS_CONTEXT_NAME, type: llvm.LLVMType.EjsValueType /* should be EjsContextType */ }, <add> { name: EJS_THIS_NAME, type: llvm.LLVMType.EjsValueType } <add>]; <add> <ide> // Set constants in the local scope. <ide> eval(definitions.consts); <ide> <ide> return isBlock(n) && n.children.length > 0; <ide> } <ide> <add>// marks an llvm function using its calling convention -- if ffi = true, we don't insert the 2 special ejs args into the call <add>function ffi_c(func) { <add> func.ffi = true; <add> func.ffi_type = "C"; <add> return func; <add>} <add> <add>function ffi_objc(func) { <add> func.ffi = true; <add> func.ffi_type = "ObjC"; <add> return func; <add>} <add> <ide> function NodeVisitor(module) { <ide> this.module = module; <ide> this.topScript = true; <ide> <ide> this.current_scope = {}; <ide> <del> this.ejs_number_new = module.getOrInsertExternalFunction("_ejs_number_new", llvm.LLVMType.EjsValueType, llvm.LLVMType.doubleType); <del> this.ejs_string_new_utf8 = module.getOrInsertExternalFunction("_ejs_string_new_utf8", llvm.LLVMType.EjsValueType, llvm.LLVMType.stringType); <del> this.ejs_print = module.getOrInsertExternalFunction("_ejs_print", llvm.LLVMType.voidType, llvm.LLVMType.EjsValueType); <del> this.ejs_op_add = module.getOrInsertExternalFunction("_ejs_op_add", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); <del> this.ejs_op_sub = module.getOrInsertExternalFunction("_ejs_op_sub", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); <del> this.ejs_op_or = module.getOrInsertExternalFunction("_ejs_op_or", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); <del> this.ejs_op_strict_eq = module.getOrInsertExternalFunction("_ejs_op_strict_eq", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); <del> this.ejs_truthy = module.getOrInsertExternalFunction("_ejs_truthy", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.boolType.pointerTo()); <del> <del> this.ejs_object_setprop = module.getOrInsertExternalFunction("_ejs_object_setprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType); <del> this.ejs_object_getprop = module.getOrInsertExternalFunction("_ejs_object_getprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo()); <add> // build up our runtime method table <add> this.ejs = { <add> invoke_closure: [ <add> ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_0", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type)), <add> ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_1", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType)), <add> ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_2", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), <add> ffi_c(module.getOrInsertExternalFunction("_ejs_invoke_closure_3", llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.int32Type, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)) <add> ], <add> <add> number_new: ffi_c(module.getOrInsertExternalFunction("_ejs_number_new", llvm.LLVMType.EjsValueType, llvm.LLVMType.doubleType)), <add> string_new_utf8: ffi_c(module.getOrInsertExternalFunction("_ejs_string_new_utf8", llvm.LLVMType.EjsValueType, llvm.LLVMType.stringType)), <add> closure_new: ffi_c(module.getOrInsertExternalFunction("_ejs_closure_new", llvm.LLVMType.EjsFuncType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), <add> print: ffi_c(module.getOrInsertExternalFunction("_ejs_print", llvm.LLVMType.voidType, llvm.LLVMType.EjsValueType)), <add> op_add: ffi_c(module.getOrInsertExternalFunction("_ejs_op_add", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), <add> op_sub: ffi_c(module.getOrInsertExternalFunction("_ejs_op_sub", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), <add> op_or: ffi_c(module.getOrInsertExternalFunction("_ejs_op_or", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), <add> op_strict_eq: ffi_c(module.getOrInsertExternalFunction("_ejs_op_strict_eq", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())), <add> truthy: ffi_c(module.getOrInsertExternalFunction("_ejs_truthy", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.boolType.pointerTo())), <add> object_setprop: ffi_c(module.getOrInsertExternalFunction("_ejs_object_setprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType)), <add> object_getprop: ffi_c(module.getOrInsertExternalFunction("_ejs_object_getprop", llvm.LLVMType.boolType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType, llvm.LLVMType.EjsValueType.pointerTo())) <add> }; <ide> } <ide> <ide> NodeVisitor.prototype.pushScope = function(new_scope) { <ide> this.current_scope = this.current_scope[PARENT_SCOPE_KEY]; <ide> }; <ide> <add>NodeVisitor.prototype.createAlloca = function (func, type, name) { <add> let saved_insert_point = llvm.IRBuilder.getInsertBlock(); <add> llvm.IRBuilder.setInsertPoint(func.entry_bb); <add> let alloca = llvm.IRBuilder.createAlloca (type, name); <add> llvm.IRBuilder.setInsertPoint(saved_insert_point); <add> return alloca; <add>}; <add> <add>NodeVisitor.prototype.createAllocas = function (func, names, scope) { <add> let allocas = []; <add> <add> // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us <add> let saved_insert_point = llvm.IRBuilder.getInsertBlock(); <add> llvm.IRBuilder.setInsertPoint(func.entry_bb); <add> <add> for (let i = 0, j = names.length; i < j; i++) { <add> let name = names[i].name; <add> if (!scope[name]) { <add> allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+name); <add> scope[name] = allocas[i]; <add> } <add> } <add> <add> // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations <add> llvm.IRBuilder.setInsertPoint (saved_insert_point); <add> <add> return allocas; <add>}; <add> <add> <ide> NodeVisitor.prototype.visitScript = function(n,nc) { <ide> let top = this.topScript; <ide> this.topScript = false; <ide> this.visit(funcs[i]); <ide> } <ide> <del> var ir_func = top ? this.module.getOrInsertFunction("_ejs_script", 0) : this.currentFunction; <add> let ir_func = top ? this.module.getOrInsertFunction("_ejs_script", BUILTIN_ARGS.length) : this.currentFunction; <add> let ir_args = ir_func.getArgs(); <ide> if (top) { <ide> // XXX this block needs reworking to mirror what happens in visitFunction (particularly the distinction between entry/body_bb) <ide> this.currentFunction = ir_func; <ide> var entry_bb = llvm.BasicBlock.create ("entry", ir_func); <ide> llvm.IRBuilder.setInsertPoint(entry_bb); <ide> ir_func.entry_bb = entry_bb; <del> var scope = {}; <del> ir_func.topScope = scope; <del> this.current_scope = scope; <add> var new_scope = {}; <add> ir_func.topScope = new_scope; <add> this.current_scope = new_scope; <add> <add> let allocas = []; <add> for (let i = 0, j = BUILTIN_ARGS.length; i < j; i++) { <add> ir_args[i].setName(BUILTIN_ARGS[i].name); <add> allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+BUILTIN_ARGS[i].name); <add> new_scope[BUILTIN_ARGS[i].name] = allocas[i]; <add> llvm.IRBuilder.createStore (ir_args[i], allocas[i]); <add> } <ide> } <ide> <ide> for (let i = 0, j = nonfunc.length; i < j; i++) { <ide> NodeVisitor.prototype.visitIf = function(n,nc) { <ide> <ide> // first we convert our conditional EJSValue to a boolean <del> let get_truthy = this.module.getFunction("_ejs_truthy"); <del> let truthy_stackalloc = llvm.IRBuilder.createAlloca(llvm.LLVMType.boolType, "truthy_result"); <del> llvm.IRBuilder.createCall(get_truthy, [this.visit(n.condition), truthy_stackalloc], "cond_truthy"); <add> let truthy_stackalloc = this.createAlloca(this.currentFunction, llvm.LLVMType.boolType, "truthy_result"); <add> llvm.IRBuilder.createCall(this.ejs.truthy, [this.visit(n.condition), truthy_stackalloc], "cond_truthy"); <ide> <ide> let cond_truthy = llvm.IRBuilder.createLoad(truthy_stackalloc, "truthy_load"); <ide> <ide> return llvm.IRBuilder.createRet(this.visit(n.value)); <ide> }; <ide> <del>NodeVisitor.prototype.createAllocasForDecls = function (n,nc,scope) { <del> let allocas = []; <del> <del> for (let i = 0, j = nc.length; i < j; i++) { <del> let name = nc[i].name; <del> if (!scope[name]) { <del> allocas[i] = llvm.IRBuilder.createAlloca (llvm.LLVMType.EjsValueType, "local_"+name); <del> scope[name] = allocas[i]; <del> } <del> } <del> <del> return allocas; <del>}; <del> <ide> NodeVisitor.prototype.visitVar = function(n,nc) { <ide> // vars are hoisted to the containing function's toplevel scope <ide> let scope = this.currentFunction.topScope; <ide> <del> // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us <del> let insertBlock = llvm.IRBuilder.getInsertBlock(); <del> llvm.IRBuilder.setInsertPoint(this.currentFunction.entry_bb); <del> <del> let allocas = this.createAllocasForDecls(n, nc, scope); <del> <del> // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations <del> llvm.IRBuilder.setInsertPoint (insertBlock); <add> let allocas = this.createAllocas(this.currentFunction, nc, scope); <ide> <ide> for (let i = 0, j = nc.length; i < j; i++) { <del> llvm.IRBuilder.createStore (this.visit(nc[i].initializer), allocas[i]); <add> let initializer = this.visit(nc[i].initializer); <add> <add> let init_needs_closure = (initializer.toString() === "[object LLVMFunction]"); <add> <add> if (init_needs_closure) { <add> initializer = llvm.IRBuilder.createCall(this.ejs.closure_new, [llvm.IRBuilder.createPointerCast(initializer, llvm.LLVMType.EjsFuncType, "castfunc"), llvm.Constant.getNull(llvm.LLVMType.EjsValueType)/*XXX*/], "closure"); <add> } <add> <add> llvm.IRBuilder.createStore (initializer, allocas[i]); <ide> } <ide> }; <ide> <ide> // lets are not hoisted to the containing function's toplevel, but instead are bound in the lexical block they inhabit <ide> let scope = this.current_scope; <ide> <del> // the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us <del> let insertBlock = llvm.IRBuilder.getInsertBlock(); <del> llvm.IRBuilder.setInsertPoint(this.currentFunction.entry_bb); <del> <del> let allocas = this.createAllocasForDecls(n, nc, scope); <del> <del> // reinstate the IRBuilder to its previous insert point so we can insert the actual initializations <del> llvm.IRBuilder.setInsertPoint (insertBlock); <add> let allocas = this.createAllocas(this.currentFunction, nc, scope); <ide> <ide> for (let i = 0, j = nc.length; i < j; i++) { <ide> llvm.IRBuilder.createStore (this.visit(nc[i].initializer), allocas[i]); <ide> } <ide> }; <ide> <add>NodeVisitor.prototype.createPropertyStore = function(obj,propname,rhs) { <add> // we assume propname is a string/identifier here... <add> let pname = this.visitString(propname); <add> return llvm.IRBuilder.createCall(this.ejs.object_setprop, [this.visit(obj), pname, rhs], "propstore_"+propname.value); <add>}; <add> <add>NodeVisitor.prototype.createPropertyLoad = function(obj,propname) { <add> // we assume propname is a string/identifier here... <add> let pname = this.visitString(propname); <add> let result = this.createAlloca(llvm.LLVMType.EjsValueType, "result"); <add> let rv = llvm.IRBuilder.createCall(this.ejs.object_getprop, [this.visit(obj), pname, result], "propload_"+propname.value); <add> return llvm.IRBuilder.createLoad(result, "result_propload"); <add>}; <add> <ide> NodeVisitor.prototype.visitAssign = function(n,nc) { <ide> var lhs = nc[0]; <ide> var rhs = nc[1]; <ide> <del> print (lhs); <del> <ide> if (lhs.type == IDENTIFIER) { <del> llvm.IRBuilder.createStore (this.visit(rhs), findIdentifierInScope(lhs.value, this.current_scope)); <add> return llvm.IRBuilder.createStore (this.visit(rhs), findIdentifierInScope(lhs.value, this.current_scope)); <add> } <add> else if (lhs.type == DOT) { <add> print ("creating propertystore!"); <add> <add> rhs = this.visit(rhs); <add> <add> let rhs_needs_closure = (rhs.toString() === "[object LLVMFunction]"); <add> <add> if (rhs_needs_closure) { <add> print ("creating closure"); <add> rhs = llvm.IRBuilder.createCall(this.ejs.closure_new, [llvm.IRBuilder.createPointerCast(rhs, llvm.LLVMType.EjsFuncType, "castfunc"), llvm.Constant.getNull(llvm.LLVMType.EjsValueType)/*XXX*/], "closure"); <add> print ("done creating closure"); <add> } <add> <add> return this.createPropertyStore (lhs.children[0], lhs.children[1], rhs); <ide> } <ide> else { <ide> throw "unhandled assign lhs"; <ide> }; <ide> <ide> NodeVisitor.prototype.visitFunction = function(n,nc) { <add> // save off the insert point so we can get back to it after generating this function <add> let insertBlock = llvm.IRBuilder.getInsertBlock(); <add> <ide> for (let i = 0, j = n.params.length; i < j; i++) { <ide> if (typeof (n.params[i]) !== 'string') { <ide> print ("we don't handle destructured/defaulted parameters yet"); <ide> } <ide> } <ide> <add> // XXX this methods needs to be augmented so that we can pass actual types (or the builtin args need <add> // to be reflected in jsllvm.cpp too). maybe we can pass the names to this method and it can do it all <add> // there? <add> <add> print ("visitFunction, 1"); <add> for (let i = BUILTIN_ARGS.length - 1, j = 0; i >= j; i--) { <add> n.params.unshift(BUILTIN_ARGS[i].name); <add> } <add> <add> if (!n.name || n.name == "") <add> n.name = "_ejs_anonymous"; <ide> var ir_func = this.module.getOrInsertFunction (n.name, n.params.length); <ide> this.currentFunction = ir_func; <ide> <ide> } <ide> <ide> <add> print ("visitFunction, 4"); <ide> // Create a new basic block to start insertion into. <ide> var entry_bb = llvm.BasicBlock.create ("entry", ir_func); <ide> llvm.IRBuilder.setInsertPoint(entry_bb); <ide> llvm.IRBuilder.createBr(body_bb); <ide> <ide> this.currentFunction = null; <add> <add> print ("returning function"); <add> <add> llvm.IRBuilder.setInsertPoint(insertBlock); <add> <ide> return ir_func; <ide> }; <ide> <ide> NodeVisitor.prototype.visitBinOp = function(n,nc,builtin) { <ide> let callee = this.module.getFunction(builtin); <ide> // allocate space on the stack for the result <del> let result = llvm.IRBuilder.createAlloca(llvm.LLVMType.EjsValueType, "result_" + builtin); <add> let result = this.createAlloca(this.currentFunction, llvm.LLVMType.EjsValueType, "result_" + builtin); <ide> // call the add method <ide> let rv = llvm.IRBuilder.createCall(callee, [this.visit(nc[0]), this.visit(nc[1]), result], "result"); <ide> // load and return the result <ide> return llvm.IRBuilder.createLoad(result, "result_"+builtin+"_load"); <ide> }; <ide> <add>NodeVisitor.prototype.createLoadThis = function () { <add> let _this = this.current_scope[EJS_THIS_NAME]; <add> return llvm.IRBuilder.createLoad (this.current_scope[EJS_THIS_NAME], "load_this"); <add>}; <add> <add>NodeVisitor.prototype.createLoadContext = function () { <add> if (!this.current_scope[EJS_CONTEXT_NAME]) <add> print ("die die die"); <add> return llvm.IRBuilder.createLoad (this.current_scope[EJS_CONTEXT_NAME], "load_context"); <add>}; <add> <ide> NodeVisitor.prototype.visitCall = function(n,nc) { <add> print ("visitCall " + nc[0]); <ide> let callee = this.visit (nc[0]); <add> let args = this.visit (nc[1]); <add> <add> if (callee.type && callee.type == DOT) { <add> print ("creating property load!"); <add> callee = this.createPropertyLoad (callee.children[0], callee.children[1]); <add> } <add> <add> // XXX this needs to be a better instanceof check <add> let callee_is_closure = (callee.toString() !== "[object LLVMFunction]"); <add> <add> // At this point we assume callee is a function object <add> <add> let compiled_arg_start; <add> if (callee_is_closure) { <add> print ("loading closure args"); <add> compiled_arg_start = 3; // closure invokers take the EJSContext and an arg length <add> args.unshift(llvm.Constant.getIntegerValue(llvm.LLVMType.int32Type, args.length)); <add> args.unshift(callee); <add> args.unshift(this.createLoadContext()); <add> } <add> else if (!callee.ffi) { <add> print ("loading this and context"); <add> // we insert the extra BUILTIN_ARGS since we're calling a JS function <add> args.unshift(this.createLoadThis()); <add> args.unshift(this.createLoadContext()); <add> <add> compiled_arg_start = 2; <add> print ("done loading this and context"); <add> } <add> else { <add> print ("ffi function, not loading this and context"); <add> compiled_arg_start = 0; <add> } <add> <add> print ("callee = " + callee.toString()); <add> <add> let argv = []; <add> for (let i = 0, j = args.length; i < j; i++) { <add> if (i < compiled_arg_start) <add> argv[i] = args[i]; <add> else <add> argv[i] = this.visit(args[i]); <add> } <add> <add> if (callee_is_closure) { <add> print (1); <add> let invoke_fun = this.ejs.invoke_closure[argv.length-compiled_arg_start]; <add> print ("2 invoke_fun = this.ejs.invoke_closure[" + (argv.length-compiled_arg_start) + "]"); <add> let rv = llvm.IRBuilder.createCall(invoke_fun, argv, "calltmp"); <add> print (3); <add> return rv; <add> } <add> else { <add> // we're dealing with a function here <add> if (callee.argSize() !== args.length) { <add> // this isn't invalid in JS. if argSize > args.length, the args are undefined. <add> // if argSize < args.length, the args are still passed <add> } <add> return llvm.IRBuilder.createCall(callee, argv, callee.returnType().isVoid() ? "" : "calltmp"); <add> } <add>}; <add> <add>NodeVisitor.prototype.visitNew = function(n,nc) { <add> let ctor = this.visit (nc[0]); <ide> let args = this.visit (nc[1]); <ide> <ide> // At this point we assume callee is a function object <ide> argv[i] = this.visit(args[i]); <ide> } <ide> <del> let rv = llvm.IRBuilder.createCall(callee, argv, callee.returnType().isVoid() ? "" : "calltmp"); <del> return rv; <del>}; <del> <del>NodeVisitor.prototype.visitNew = function(n,nc) { <del> let ctor = this.visit (nc[0]); <del> let args = this.visit (nc[1]); <del> <del> // At this point we assume callee is a function object <del> if (callee.argSize() !== args.length) { <del> // this isn't invalid in JS. if argSize > args.length, the args are undefined. <del> // if argSize < args.length, the args are still passed <del> } <del> <del> let argv = []; <del> for (let i = 0, j = args.length; i < j; i++) { <del> argv[i] = this.visit(args[i]); <del> } <del> <ide> let rv = llvm.IRBuilder.createCall(callee, argv, "newtmp"); <ide> return rv; <add>}; <add> <add>NodeVisitor.prototype.visitPropertyAccess = function(n,nc) { <add> print ("property access: " + nc[1].value); <add> return n; <add>}; <add> <add>NodeVisitor.prototype.visitThis = function(n, nc) { <add> print ("visitThis"); <add> return this.createLoadThis(); <ide> }; <ide> <ide> function findIdentifierInScope (ident, scope) { <ide> return llvm.IRBuilder.createLoad(alloca, "load_"+val); <ide> } <ide> <add> let func = null; <add> <ide> // we should probably insert a global scope at the toplevel (above the actual user-level global scope) that includes all these renamings/functions? <del> if (val == "print") <del> val = "_ejs_print"; <del> <del> var func = this.module.getFunction(val); <add> if (val == "print") { <add> func = this.ejs.print; <add> } <add> else { <add> func = this.module.getFunction(val); <add> } <add> <ide> if (func) <ide> return func; <ide> <ide> <ide> NodeVisitor.prototype.visitNumber = function(n,nc) { <ide> let c = llvm.ConstantFP.getDouble(n.value); <del> let call = llvm.IRBuilder.createCall(this.ejs_number_new, [c], "numtmp"); <add> let call = llvm.IRBuilder.createCall(this.ejs.number_new, [c], "numtmp"); <ide> return call; <ide> }; <ide> <ide> NodeVisitor.prototype.visitString = function(n,nc) { <add> print ("visitString"); <ide> let c = llvm.IRBuilder.createGlobalStringPtr(n.value, "strconst"); <del> let call = llvm.IRBuilder.createCall(this.ejs_string_new_utf8, [c], "strtmp"); <add> let call = llvm.IRBuilder.createCall(this.ejs.string_new_utf8, [c], "strtmp"); <ide> return call; <ide> }; <ide> <ide> case UNARY_MINUS: <ide> case INCREMENT: <ide> case DECREMENT: <del> case DOT: print ("DOT"); break; <add> case DOT: return this.visitPropertyAccess(n,nc); <ide> case INDEX: break; <ide> case NEW_WITH_ARGS: <ide> case ARRAY_INIT: <ide> case COMP_TAIL: <ide> case OBJECT_INIT: <ide> case NULL: <del> case THIS: print ("THIS"); break; <add> case THIS: return this.visitThis(n,nc); <ide> case TRUE: <ide> case FALSE: <ide> case REGEXP:
Java
apache-2.0
0d6187ed3fd47a2a6185f0a36f853080e7412573
0
Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0,Wajihulhassan/Hadoop-2.7.0
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServiceProtos.SchedulerResourceTypes; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationConstants; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppRejectedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt.ContainersAndNMTokensAllocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.QueueEntitlement; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerExpiredSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeResourceUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * A scheduler that schedules resources between a set of queues. The scheduler * keeps track of the resources used by each queue, and attempts to maintain * fairness by scheduling tasks at queues whose allocations are farthest below * an ideal fair distribution. * * The fair scheduler supports hierarchical queues. All queues descend from a * queue named "root". Available resources are distributed among the children * of the root queue in the typical fair scheduling fashion. Then, the children * distribute the resources assigned to them to their children in the same * fashion. Applications may only be scheduled on leaf queues. Queues can be * specified as children of other queues by placing them as sub-elements of their * parents in the fair scheduler configuration file. * * A queue's name starts with the names of its parents, with periods as * separators. So a queue named "queue1" under the root named, would be * referred to as "root.queue1", and a queue named "queue2" under a queue * named "parent1" would be referred to as "root.parent1.queue2". */ @LimitedPrivate("yarn") @Unstable @SuppressWarnings("unchecked") public class FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { private FairSchedulerConfiguration conf; private Resource incrAllocation; private QueueManager queueMgr; private volatile Clock clock; private boolean usePortForNodeName; private static final Log LOG = LogFactory.getLog(FairScheduler.class); private static final ResourceCalculator RESOURCE_CALCULATOR = new DefaultResourceCalculator(); private static final ResourceCalculator DOMINANT_RESOURCE_CALCULATOR = new DominantResourceCalculator(); // Value that container assignment methods return when a container is // reserved public static final Resource CONTAINER_RESERVED = Resources.createResource(-1); // How often fair shares are re-calculated (ms) protected long updateInterval; private final int UPDATE_DEBUG_FREQUENCY = 5; private int updatesToSkipForDebug = UPDATE_DEBUG_FREQUENCY; @VisibleForTesting Thread updateThread; @VisibleForTesting Thread schedulingThread; // timeout to join when we stop this service protected final long THREAD_JOIN_TIMEOUT_MS = 1000; // Aggregate metrics FSQueueMetrics rootMetrics; FSOpDurations fsOpDurations; // Time when we last updated preemption vars protected long lastPreemptionUpdateTime; // Time we last ran preemptTasksIfNecessary private long lastPreemptCheckTime; // Preemption related variables protected boolean preemptionEnabled; protected float preemptionUtilizationThreshold; // How often tasks are preempted protected long preemptionInterval; // ms to wait before force killing stuff (must be longer than a couple // of heartbeats to give task-kill commands a chance to act). protected long waitTimeBeforeKill; // Containers whose AMs have been warned that they will be preempted soon. private List<RMContainer> warnedContainers = new ArrayList<RMContainer>(); protected boolean sizeBasedWeight; // Give larger weights to larger jobs protected WeightAdjuster weightAdjuster; // Can be null for no weight adjuster protected boolean continuousSchedulingEnabled; // Continuous Scheduling enabled or not protected int continuousSchedulingSleepMs; // Sleep time for each pass in continuous scheduling private Comparator<NodeId> nodeAvailableResourceComparator = new NodeAvailableResourceComparator(); // Node available resource comparator protected double nodeLocalityThreshold; // Cluster threshold for node locality protected double rackLocalityThreshold; // Cluster threshold for rack locality protected long nodeLocalityDelayMs; // Delay for node locality protected long rackLocalityDelayMs; // Delay for rack locality private FairSchedulerEventLog eventLog; // Machine-readable event log protected boolean assignMultiple; // Allocate multiple containers per // heartbeat protected int maxAssign; // Max containers to assign per heartbeat /* Start -Wajih Measuring decision timings*/ public int dec_array_size=10000; public int[] decision_time; public long no_of_decisions; /* End - Wajih*/ @VisibleForTesting final MaxRunningAppsEnforcer maxRunningEnforcer; private AllocationFileLoaderService allocsLoader; @VisibleForTesting AllocationConfiguration allocConf; public FairScheduler() { super(FairScheduler.class.getName()); clock = new SystemClock(); allocsLoader = new AllocationFileLoaderService(); queueMgr = new QueueManager(this); maxRunningEnforcer = new MaxRunningAppsEnforcer(this); /*Start Wajih Measuring decision timings*/ dec_array_size=10000; decision_time = new int[dec_array_size]; /* End Wajih */ } private void validateConf(Configuration conf) { // validate scheduler memory allocation setting int minMem = conf.getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); int maxMem = conf.getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB); if (minMem < 0 || minMem > maxMem) { throw new YarnRuntimeException("Invalid resource scheduler memory" + " allocation configuration" + ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB + "=" + minMem + ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + "=" + maxMem + ", min should equal greater than 0" + ", max should be no smaller than min."); } // validate scheduler vcores allocation setting int minVcores = conf.getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); int maxVcores = conf.getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); if (minVcores < 0 || minVcores > maxVcores) { throw new YarnRuntimeException("Invalid resource scheduler vcores" + " allocation configuration" + ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES + "=" + minVcores + ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES + "=" + maxVcores + ", min should equal greater than 0" + ", max should be no smaller than min."); } } public FairSchedulerConfiguration getConf() { return conf; } public QueueManager getQueueManager() { return queueMgr; } /** * Thread which calls {@link FairScheduler#update()} every * <code>updateInterval</code> milliseconds. */ private class UpdateThread extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(updateInterval); long start = getClock().getTime(); update(); preemptTasksIfNecessary(); long duration = getClock().getTime() - start; fsOpDurations.addUpdateThreadRunDuration(duration); } catch (InterruptedException ie) { LOG.warn("Update thread interrupted. Exiting."); return; } catch (Exception e) { LOG.error("Exception in fair scheduler UpdateThread", e); } } } } /** * Thread which attempts scheduling resources continuously, * asynchronous to the node heartbeats. */ private class ContinuousSchedulingThread extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { continuousSchedulingAttempt(); Thread.sleep(getContinuousSchedulingSleepMs()); } catch (InterruptedException e) { LOG.warn("Continuous scheduling thread interrupted. Exiting.", e); return; } } } } /** * Recompute the internal variables used by the scheduler - per-job weights, * fair shares, deficits, minimum slot allocations, and amount of used and * required resources per job. */ protected synchronized void update() { long start = getClock().getTime(); updateStarvationStats(); // Determine if any queues merit preemption FSQueue rootQueue = queueMgr.getRootQueue(); // Recursively update demands for all queues rootQueue.updateDemand(); rootQueue.setFairShare(clusterResource); // Recursively compute fair shares for all queues // and update metrics rootQueue.recomputeShares(); updateRootQueueMetrics(); if (LOG.isDebugEnabled()) { if (--updatesToSkipForDebug < 0) { updatesToSkipForDebug = UPDATE_DEBUG_FREQUENCY; LOG.debug("Cluster Capacity: " + clusterResource + " Allocations: " + rootMetrics.getAllocatedResources() + " Availability: " + Resource.newInstance( rootMetrics.getAvailableMB(), rootMetrics.getAvailableVirtualCores()) + " Demand: " + rootQueue.getDemand()); } } long duration = getClock().getTime() - start; fsOpDurations.addUpdateCallDuration(duration); } /** * Update the preemption fields for all QueueScheduables, i.e. the times since * each queue last was at its guaranteed share and over its fair share * threshold for each type of task. */ private void updateStarvationStats() { lastPreemptionUpdateTime = clock.getTime(); for (FSLeafQueue sched : queueMgr.getLeafQueues()) { sched.updateStarvationStats(); } } /** * Check for queues that need tasks preempted, either because they have been * below their guaranteed share for minSharePreemptionTimeout or they have * been below their fair share threshold for the fairSharePreemptionTimeout. If * such queues exist, compute how many tasks of each type need to be preempted * and then select the right ones using preemptTasks. */ protected synchronized void preemptTasksIfNecessary() { if (!shouldAttemptPreemption()) { return; } long curTime = getClock().getTime(); if (curTime - lastPreemptCheckTime < preemptionInterval) { return; } lastPreemptCheckTime = curTime; Resource resToPreempt = Resources.clone(Resources.none()); for (FSLeafQueue sched : queueMgr.getLeafQueues()) { Resources.addTo(resToPreempt, resToPreempt(sched, curTime)); } if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, resToPreempt, Resources.none())) { preemptResources(resToPreempt); } } /** * Preempt a quantity of resources. Each round, we start from the root queue, * level-by-level, until choosing a candidate application. * The policy for prioritizing preemption for each queue depends on its * SchedulingPolicy: (1) fairshare/DRF, choose the ChildSchedulable that is * most over its fair share; (2) FIFO, choose the childSchedulable that is * latest launched. * Inside each application, we further prioritize preemption by choosing * containers with lowest priority to preempt. * We make sure that no queue is placed below its fair share in the process. */ protected void preemptResources(Resource toPreempt) { long start = getClock().getTime(); if (Resources.equals(toPreempt, Resources.none())) { return; } // Scan down the list of containers we've already warned and kill them // if we need to. Remove any containers from the list that we don't need // or that are no longer running. Iterator<RMContainer> warnedIter = warnedContainers.iterator(); while (warnedIter.hasNext()) { RMContainer container = warnedIter.next(); if ((container.getState() == RMContainerState.RUNNING || container.getState() == RMContainerState.ALLOCATED) && Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, toPreempt, Resources.none())) { warnOrKillContainer(container); Resources.subtractFrom(toPreempt, container.getContainer().getResource()); } else { warnedIter.remove(); } } try { // Reset preemptedResource for each app for (FSLeafQueue queue : getQueueManager().getLeafQueues()) { queue.resetPreemptedResources(); } while (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, toPreempt, Resources.none())) { RMContainer container = getQueueManager().getRootQueue().preemptContainer(); if (container == null) { break; } else { warnOrKillContainer(container); warnedContainers.add(container); Resources.subtractFrom( toPreempt, container.getContainer().getResource()); } } } finally { // Clear preemptedResources for each app for (FSLeafQueue queue : getQueueManager().getLeafQueues()) { queue.clearPreemptedResources(); } } long duration = getClock().getTime() - start; fsOpDurations.addPreemptCallDuration(duration); } protected void warnOrKillContainer(RMContainer container) { ApplicationAttemptId appAttemptId = container.getApplicationAttemptId(); FSAppAttempt app = getSchedulerApp(appAttemptId); FSLeafQueue queue = app.getQueue(); LOG.info("Preempting container (prio=" + container.getContainer().getPriority() + "res=" + container.getContainer().getResource() + ") from queue " + queue.getName()); Long time = app.getContainerPreemptionTime(container); if (time != null) { // if we asked for preemption more than maxWaitTimeBeforeKill ms ago, // proceed with kill if (time + waitTimeBeforeKill < getClock().getTime()) { ContainerStatus status = SchedulerUtils.createPreemptedContainerStatus( container.getContainerId(), SchedulerUtils.PREEMPTED_CONTAINER); recoverResourceRequestForContainer(container); // TODO: Not sure if this ever actually adds this to the list of cleanup // containers on the RMNode (see SchedulerNode.releaseContainer()). completedContainer(container, status, RMContainerEventType.KILL); LOG.info("Killing container" + container + " (after waiting for premption for " + (getClock().getTime() - time) + "ms)"); } } else { // track the request in the FSAppAttempt itself app.addPreemption(container, getClock().getTime()); } } /** * Return the resource amount that this queue is allowed to preempt, if any. * If the queue has been below its min share for at least its preemption * timeout, it should preempt the difference between its current share and * this min share. If it has been below its fair share preemption threshold * for at least the fairSharePreemptionTimeout, it should preempt enough tasks * to get up to its full fair share. If both conditions hold, we preempt the * max of the two amounts (this shouldn't happen unless someone sets the * timeouts to be identical for some reason). */ protected Resource resToPreempt(FSLeafQueue sched, long curTime) { long minShareTimeout = sched.getMinSharePreemptionTimeout(); long fairShareTimeout = sched.getFairSharePreemptionTimeout(); Resource resDueToMinShare = Resources.none(); Resource resDueToFairShare = Resources.none(); if (curTime - sched.getLastTimeAtMinShare() > minShareTimeout) { Resource target = Resources.min(RESOURCE_CALCULATOR, clusterResource, sched.getMinShare(), sched.getDemand()); resDueToMinShare = Resources.max(RESOURCE_CALCULATOR, clusterResource, Resources.none(), Resources.subtract(target, sched.getResourceUsage())); } if (curTime - sched.getLastTimeAtFairShareThreshold() > fairShareTimeout) { Resource target = Resources.min(RESOURCE_CALCULATOR, clusterResource, sched.getFairShare(), sched.getDemand()); resDueToFairShare = Resources.max(RESOURCE_CALCULATOR, clusterResource, Resources.none(), Resources.subtract(target, sched.getResourceUsage())); } Resource resToPreempt = Resources.max(RESOURCE_CALCULATOR, clusterResource, resDueToMinShare, resDueToFairShare); if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, resToPreempt, Resources.none())) { String message = "Should preempt " + resToPreempt + " res for queue " + sched.getName() + ": resDueToMinShare = " + resDueToMinShare + ", resDueToFairShare = " + resDueToFairShare; LOG.info(message); } return resToPreempt; } public synchronized RMContainerTokenSecretManager getContainerTokenSecretManager() { return rmContext.getContainerTokenSecretManager(); } // synchronized for sizeBasedWeight public synchronized ResourceWeights getAppWeight(FSAppAttempt app) { double weight = 1.0; if (sizeBasedWeight) { // Set weight based on current memory demand weight = Math.log1p(app.getDemand().getMemory()) / Math.log(2); } weight *= app.getPriority().getPriority(); if (weightAdjuster != null) { // Run weight through the user-supplied weightAdjuster weight = weightAdjuster.adjustWeight(app, weight); } ResourceWeights resourceWeights = app.getResourceWeights(); resourceWeights.setWeight((float)weight); return resourceWeights; } public Resource getIncrementResourceCapability() { return incrAllocation; } private FSSchedulerNode getFSSchedulerNode(NodeId nodeId) { return nodes.get(nodeId); } public double getNodeLocalityThreshold() { return nodeLocalityThreshold; } public double getRackLocalityThreshold() { return rackLocalityThreshold; } public long getNodeLocalityDelayMs() { return nodeLocalityDelayMs; } public long getRackLocalityDelayMs() { return rackLocalityDelayMs; } public boolean isContinuousSchedulingEnabled() { return continuousSchedulingEnabled; } public synchronized int getContinuousSchedulingSleepMs() { return continuousSchedulingSleepMs; } public Clock getClock() { return clock; } @VisibleForTesting void setClock(Clock clock) { this.clock = clock; } public FairSchedulerEventLog getEventLog() { return eventLog; } /** * Add a new application to the scheduler, with a given id, queue name, and * user. This will accept a new app even if the user or queue is above * configured limits, but the app will not be marked as runnable. */ protected synchronized void addApplication(ApplicationId applicationId, String queueName, String user, boolean isAppRecovering) { if (queueName == null || queueName.isEmpty()) { String message = "Reject application " + applicationId + " submitted by user " + user + " with an empty queue name."; LOG.info(message); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return; } if (queueName.startsWith(".") || queueName.endsWith(".")) { String message = "Reject application " + applicationId + " submitted by user " + user + " with an illegal queue name " + queueName + ". " + "The queue name cannot start/end with period."; LOG.info(message); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return; } RMApp rmApp = rmContext.getRMApps().get(applicationId); FSLeafQueue queue = assignToQueue(rmApp, queueName, user); if (queue == null) { return; } // Enforce ACLs UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(user); if (!queue.hasAccess(QueueACL.SUBMIT_APPLICATIONS, userUgi) && !queue.hasAccess(QueueACL.ADMINISTER_QUEUE, userUgi)) { String msg = "User " + userUgi.getUserName() + " cannot submit applications to queue " + queue.getName(); LOG.info(msg); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, msg)); return; } SchedulerApplication<FSAppAttempt> application = new SchedulerApplication<FSAppAttempt>(queue, user); applications.put(applicationId, application); queue.getMetrics().submitApp(user); LOG.info("Accepted application " + applicationId + " from user: " + user + ", in queue: " + queueName + ", currently num of applications: " + applications.size()); if (isAppRecovering) { if (LOG.isDebugEnabled()) { LOG.debug(applicationId + " is recovering. Skip notifying APP_ACCEPTED"); } } else { rmContext.getDispatcher().getEventHandler() .handle(new RMAppEvent(applicationId, RMAppEventType.APP_ACCEPTED)); } } /** * Add a new application attempt to the scheduler. */ protected synchronized void addApplicationAttempt( ApplicationAttemptId applicationAttemptId, boolean transferStateFromPreviousAttempt, boolean isAttemptRecovering) { SchedulerApplication<FSAppAttempt> application = applications.get(applicationAttemptId.getApplicationId()); String user = application.getUser(); FSLeafQueue queue = (FSLeafQueue) application.getQueue(); FSAppAttempt attempt = new FSAppAttempt(this, applicationAttemptId, user, queue, new ActiveUsersManager(getRootQueueMetrics()), rmContext); if (transferStateFromPreviousAttempt) { attempt.transferStateFromPreviousAttempt(application .getCurrentAppAttempt()); } application.setCurrentAppAttempt(attempt); boolean runnable = maxRunningEnforcer.canAppBeRunnable(queue, user); queue.addApp(attempt, runnable); if (runnable) { maxRunningEnforcer.trackRunnableApp(attempt); } else { maxRunningEnforcer.trackNonRunnableApp(attempt); } queue.getMetrics().submitAppAttempt(user); LOG.info("Added Application Attempt " + applicationAttemptId + " to scheduler from user: " + user); if (isAttemptRecovering) { if (LOG.isDebugEnabled()) { LOG.debug(applicationAttemptId + " is recovering. Skipping notifying ATTEMPT_ADDED"); } } else { rmContext.getDispatcher().getEventHandler().handle( new RMAppAttemptEvent(applicationAttemptId, RMAppAttemptEventType.ATTEMPT_ADDED)); } } /** * Helper method that attempts to assign the app to a queue. The method is * responsible to call the appropriate event-handler if the app is rejected. */ @VisibleForTesting FSLeafQueue assignToQueue(RMApp rmApp, String queueName, String user) { FSLeafQueue queue = null; String appRejectMsg = null; try { QueuePlacementPolicy placementPolicy = allocConf.getPlacementPolicy(); queueName = placementPolicy.assignAppToQueue(queueName, user); if (queueName == null) { appRejectMsg = "Application rejected by queue placement policy"; } else { queue = queueMgr.getLeafQueue(queueName, true); if (queue == null) { appRejectMsg = queueName + " is not a leaf queue"; } } } catch (IOException ioe) { appRejectMsg = "Error assigning app to queue " + queueName; } if (appRejectMsg != null && rmApp != null) { LOG.error(appRejectMsg); rmContext.getDispatcher().getEventHandler().handle( new RMAppRejectedEvent(rmApp.getApplicationId(), appRejectMsg)); return null; } if (rmApp != null) { rmApp.setQueue(queue.getName()); } else { LOG.error("Couldn't find RM app to set queue name on"); } return queue; } private synchronized void removeApplication(ApplicationId applicationId, RMAppState finalState) { SchedulerApplication<FSAppAttempt> application = applications.get(applicationId); if (application == null){ LOG.warn("Couldn't find application " + applicationId); return; } application.stop(finalState); applications.remove(applicationId); } private synchronized void removeApplicationAttempt( ApplicationAttemptId applicationAttemptId, RMAppAttemptState rmAppAttemptFinalState, boolean keepContainers) { LOG.info("Application " + applicationAttemptId + " is done." + " finalState=" + rmAppAttemptFinalState); SchedulerApplication<FSAppAttempt> application = applications.get(applicationAttemptId.getApplicationId()); FSAppAttempt attempt = getSchedulerApp(applicationAttemptId); if (attempt == null || application == null) { LOG.info("Unknown application " + applicationAttemptId + " has completed!"); return; } // Release all the running containers for (RMContainer rmContainer : attempt.getLiveContainers()) { if (keepContainers && rmContainer.getState().equals(RMContainerState.RUNNING)) { // do not kill the running container in the case of work-preserving AM // restart. LOG.info("Skip killing " + rmContainer.getContainerId()); continue; } completedContainer(rmContainer, SchedulerUtils.createAbnormalContainerStatus( rmContainer.getContainerId(), SchedulerUtils.COMPLETED_APPLICATION), RMContainerEventType.KILL); } // Release all reserved containers for (RMContainer rmContainer : attempt.getReservedContainers()) { completedContainer(rmContainer, SchedulerUtils.createAbnormalContainerStatus( rmContainer.getContainerId(), "Application Complete"), RMContainerEventType.KILL); } // Clean up pending requests, metrics etc. attempt.stop(rmAppAttemptFinalState); // Inform the queue FSLeafQueue queue = queueMgr.getLeafQueue(attempt.getQueue() .getQueueName(), false); boolean wasRunnable = queue.removeApp(attempt); if (wasRunnable) { maxRunningEnforcer.untrackRunnableApp(attempt); maxRunningEnforcer.updateRunnabilityOnAppRemoval(attempt, attempt.getQueue()); } else { maxRunningEnforcer.untrackNonRunnableApp(attempt); } } /** * Clean up a completed container. */ @Override protected synchronized void completedContainer(RMContainer rmContainer, ContainerStatus containerStatus, RMContainerEventType event) { if (rmContainer == null) { LOG.info("Null container completed..."); return; } Container container = rmContainer.getContainer(); // Get the application for the finished container FSAppAttempt application = getCurrentAttemptForContainer(container.getId()); ApplicationId appId = container.getId().getApplicationAttemptId().getApplicationId(); if (application == null) { LOG.info("Container " + container + " of" + " unknown application attempt " + appId + " completed with event " + event); return; } // Get the node on which the container was allocated FSSchedulerNode node = getFSSchedulerNode(container.getNodeId()); if (rmContainer.getState() == RMContainerState.RESERVED) { application.unreserve(rmContainer.getReservedPriority(), node); } else { application.containerCompleted(rmContainer, containerStatus, event); node.releaseContainer(container); updateRootQueueMetrics(); } LOG.info("Application attempt " + application.getApplicationAttemptId() + " released container " + container.getId() + " on node: " + node + " with event: " + event); } private synchronized void addNode(RMNode node) { FSSchedulerNode schedulerNode = new FSSchedulerNode(node, usePortForNodeName); nodes.put(node.getNodeID(), schedulerNode); Resources.addTo(clusterResource, node.getTotalCapability()); updateRootQueueMetrics(); updateMaximumAllocation(schedulerNode, true); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); LOG.info("Added node " + node.getNodeAddress() + " cluster capacity: " + clusterResource); } private synchronized void removeNode(RMNode rmNode) { FSSchedulerNode node = getFSSchedulerNode(rmNode.getNodeID()); // This can occur when an UNHEALTHY node reconnects if (node == null) { return; } Resources.subtractFrom(clusterResource, rmNode.getTotalCapability()); updateRootQueueMetrics(); // Remove running containers List<RMContainer> runningContainers = node.getRunningContainers(); for (RMContainer container : runningContainers) { completedContainer(container, SchedulerUtils.createAbnormalContainerStatus( container.getContainerId(), SchedulerUtils.LOST_CONTAINER), RMContainerEventType.KILL); } // Remove reservations, if any RMContainer reservedContainer = node.getReservedContainer(); if (reservedContainer != null) { completedContainer(reservedContainer, SchedulerUtils.createAbnormalContainerStatus( reservedContainer.getContainerId(), SchedulerUtils.LOST_CONTAINER), RMContainerEventType.KILL); } nodes.remove(rmNode.getNodeID()); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); updateMaximumAllocation(node, false); LOG.info("Removed node " + rmNode.getNodeAddress() + " cluster capacity: " + clusterResource); } @Override public Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals) { // Make sure this application exists FSAppAttempt application = getSchedulerApp(appAttemptId); if (application == null) { LOG.info("Calling allocate on removed " + "or non existant application " + appAttemptId); return EMPTY_ALLOCATION; } // Sanity check SchedulerUtils.normalizeRequests(ask, DOMINANT_RESOURCE_CALCULATOR, clusterResource, minimumAllocation, getMaximumResourceCapability(), incrAllocation); // Set amResource for this app if (!application.getUnmanagedAM() && ask.size() == 1 && application.getLiveContainers().isEmpty()) { application.setAMResource(ask.get(0).getCapability()); } // Release containers releaseContainers(release, application); synchronized (application) { if (!ask.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("allocate: pre-update" + " applicationAttemptId=" + appAttemptId + " application=" + application.getApplicationId()); } application.showRequests(); // Update application requests application.updateResourceRequests(ask); application.showRequests(); } if (LOG.isDebugEnabled()) { LOG.debug("allocate: post-update" + " applicationAttemptId=" + appAttemptId + " #ask=" + ask.size() + " reservation= " + application.getCurrentReservation()); LOG.debug("Preempting " + application.getPreemptionContainers().size() + " container(s)"); } Set<ContainerId> preemptionContainerIds = new HashSet<ContainerId>(); for (RMContainer container : application.getPreemptionContainers()) { preemptionContainerIds.add(container.getContainerId()); } application.updateBlacklist(blacklistAdditions, blacklistRemovals); ContainersAndNMTokensAllocation allocation = application.pullNewlyAllocatedContainersAndNMTokens(); Resource headroom = application.getHeadroom(); application.setApplicationHeadroomForMetrics(headroom); return new Allocation(allocation.getContainerList(), headroom, preemptionContainerIds, null, null, allocation.getNMTokenList()); } } /** * Process a heartbeat update from a node. */ private synchronized void nodeUpdate(RMNode nm) { long start = getClock().getTime(); if (LOG.isDebugEnabled()) { LOG.debug("nodeUpdate: " + nm + " cluster capacity: " + clusterResource); } eventLog.log("HEARTBEAT", nm.getHostName()); FSSchedulerNode node = getFSSchedulerNode(nm.getNodeID()); List<UpdatedContainerInfo> containerInfoList = nm.pullContainerUpdates(); List<ContainerStatus> newlyLaunchedContainers = new ArrayList<ContainerStatus>(); List<ContainerStatus> completedContainers = new ArrayList<ContainerStatus>(); for(UpdatedContainerInfo containerInfo : containerInfoList) { newlyLaunchedContainers.addAll(containerInfo.getNewlyLaunchedContainers()); completedContainers.addAll(containerInfo.getCompletedContainers()); } // Processing the newly launched containers for (ContainerStatus launchedContainer : newlyLaunchedContainers) { containerLaunchedOnNode(launchedContainer.getContainerId(), node); } // Process completed containers for (ContainerStatus completedContainer : completedContainers) { ContainerId containerId = completedContainer.getContainerId(); LOG.debug("Container FINISHED: " + containerId); completedContainer(getRMContainer(containerId), completedContainer, RMContainerEventType.FINISHED); } /* Start Wajih Adding Timers to check decision delays*/ no_of_decisions++; /* End */ if (continuousSchedulingEnabled) { if (!completedContainers.isEmpty()) { attemptScheduling(node); } } else { /* Start Wajih Adding Timers to check decision delays*/ long beforeTime = System.currentTimeMillis(); /* End */ attemptScheduling(node); /* Start Wajih Adding Timers to check decision delays*/ long afterTime = System.currentTimeMillis(); int dec_time = (int)(afterTime-beforeTime); decision_time[dec_time]++; /* End */ } long duration = getClock().getTime() - start; fsOpDurations.addNodeUpdateDuration(duration); } void continuousSchedulingAttempt() throws InterruptedException { long start = getClock().getTime(); List<NodeId> nodeIdList = new ArrayList<NodeId>(nodes.keySet()); // Sort the nodes by space available on them, so that we offer // containers on emptier nodes first, facilitating an even spread. This // requires holding the scheduler lock, so that the space available on a // node doesn't change during the sort. synchronized (this) { Collections.sort(nodeIdList, nodeAvailableResourceComparator); } // iterate all nodes for (NodeId nodeId : nodeIdList) { FSSchedulerNode node = getFSSchedulerNode(nodeId); try { if (node != null && Resources.fitsIn(minimumAllocation, node.getAvailableResource())) { attemptScheduling(node); } } catch (Throwable ex) { LOG.error("Error while attempting scheduling for node " + node + ": " + ex.toString(), ex); } } long duration = getClock().getTime() - start; fsOpDurations.addContinuousSchedulingRunDuration(duration); } /** Sort nodes by available resource */ private class NodeAvailableResourceComparator implements Comparator<NodeId> { @Override public int compare(NodeId n1, NodeId n2) { if (!nodes.containsKey(n1)) { return 1; } if (!nodes.containsKey(n2)) { return -1; } return RESOURCE_CALCULATOR.compare(clusterResource, nodes.get(n2).getAvailableResource(), nodes.get(n1).getAvailableResource()); } } private synchronized void attemptScheduling(FSSchedulerNode node) { if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext.isSchedulerReadyForAllocatingContainers()) { return; } // Assign new containers... // 1. Check for reserved applications // 2. Schedule if there are no reservations FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); if (reservedAppSchedulable != null) { Priority reservedPriority = node.getReservedContainer().getReservedPriority(); FSQueue queue = reservedAppSchedulable.getQueue(); if (!reservedAppSchedulable.hasContainerForNode(reservedPriority, node) || !fitsInMaxShare(queue, node.getReservedContainer().getReservedResource())) { // Don't hold the reservation if app can no longer use it LOG.info("Releasing reservation that cannot be satisfied for application " + reservedAppSchedulable.getApplicationAttemptId() + " on node " + node); reservedAppSchedulable.unreserve(reservedPriority, node); reservedAppSchedulable = null; } else { // Reservation exists; try to fulfill the reservation if (LOG.isDebugEnabled()) { LOG.debug("Trying to fulfill reservation for application " + reservedAppSchedulable.getApplicationAttemptId() + " on node: " + node); } node.getReservedAppSchedulable().assignReservedContainer(node); } } if (reservedAppSchedulable == null) { // No reservation, schedule at queue which is farthest below fair share int assignedContainers = 0; while (node.getReservedContainer() == null) { boolean assignedContainer = false; if (!queueMgr.getRootQueue().assignContainer(node).equals( Resources.none())) { assignedContainers++; assignedContainer = true; } if (!assignedContainer) { break; } if (!assignMultiple) { break; } if ((assignedContainers >= maxAssign) && (maxAssign > 0)) { break; } } } updateRootQueueMetrics(); } static boolean fitsInMaxShare(FSQueue queue, Resource additionalResource) { Resource usagePlusAddition = Resources.add(queue.getResourceUsage(), additionalResource); if (!Resources.fitsIn(usagePlusAddition, queue.getMaxShare())) { return false; } FSQueue parentQueue = queue.getParent(); if (parentQueue != null) { return fitsInMaxShare(parentQueue, additionalResource); } return true; } public FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId) { return super.getApplicationAttempt(appAttemptId); } @Override public ResourceCalculator getResourceCalculator() { return RESOURCE_CALCULATOR; } /** * Subqueue metrics might be a little out of date because fair shares are * recalculated at the update interval, but the root queue metrics needs to * be updated synchronously with allocations and completions so that cluster * metrics will be consistent. */ private void updateRootQueueMetrics() { rootMetrics.setAvailableResourcesToQueue( Resources.subtract( clusterResource, rootMetrics.getAllocatedResources())); } /** * Check if preemption is enabled and the utilization threshold for * preemption is met. * * @return true if preemption should be attempted, false otherwise. */ private boolean shouldAttemptPreemption() { if (preemptionEnabled) { return (preemptionUtilizationThreshold < Math.max( (float) rootMetrics.getAllocatedMB() / clusterResource.getMemory(), (float) rootMetrics.getAllocatedVirtualCores() / clusterResource.getVirtualCores())); } return false; } @Override public QueueMetrics getRootQueueMetrics() { return rootMetrics; } @Override public void handle(SchedulerEvent event) { switch (event.getType()) { case NODE_ADDED: if (!(event instanceof NodeAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent)event; addNode(nodeAddedEvent.getAddedRMNode()); recoverContainersOnNode(nodeAddedEvent.getContainerReports(), nodeAddedEvent.getAddedRMNode()); break; case NODE_REMOVED: if (!(event instanceof NodeRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent)event; removeNode(nodeRemovedEvent.getRemovedRMNode()); break; case NODE_UPDATE: if (!(event instanceof NodeUpdateSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeUpdateSchedulerEvent nodeUpdatedEvent = (NodeUpdateSchedulerEvent)event; nodeUpdate(nodeUpdatedEvent.getRMNode()); break; case APP_ADDED: if (!(event instanceof AppAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent) event; String queueName = resolveReservationQueueName(appAddedEvent.getQueue(), appAddedEvent.getApplicationId(), appAddedEvent.getReservationID()); if (queueName != null) { addApplication(appAddedEvent.getApplicationId(), queueName, appAddedEvent.getUser(), appAddedEvent.getIsAppRecovering()); } break; case APP_REMOVED: if (!(event instanceof AppRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent)event; removeApplication(appRemovedEvent.getApplicationID(), appRemovedEvent.getFinalState()); break; case NODE_RESOURCE_UPDATE: if (!(event instanceof NodeResourceUpdateSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeResourceUpdateSchedulerEvent nodeResourceUpdatedEvent = (NodeResourceUpdateSchedulerEvent)event; updateNodeResource(nodeResourceUpdatedEvent.getRMNode(), nodeResourceUpdatedEvent.getResourceOption()); break; case APP_ATTEMPT_ADDED: if (!(event instanceof AppAttemptAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAttemptAddedSchedulerEvent appAttemptAddedEvent = (AppAttemptAddedSchedulerEvent) event; addApplicationAttempt(appAttemptAddedEvent.getApplicationAttemptId(), appAttemptAddedEvent.getTransferStateFromPreviousAttempt(), appAttemptAddedEvent.getIsAttemptRecovering()); break; case APP_ATTEMPT_REMOVED: if (!(event instanceof AppAttemptRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent = (AppAttemptRemovedSchedulerEvent) event; removeApplicationAttempt( appAttemptRemovedEvent.getApplicationAttemptID(), appAttemptRemovedEvent.getFinalAttemptState(), appAttemptRemovedEvent.getKeepContainersAcrossAppAttempts()); break; case CONTAINER_EXPIRED: if (!(event instanceof ContainerExpiredSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } ContainerExpiredSchedulerEvent containerExpiredEvent = (ContainerExpiredSchedulerEvent)event; ContainerId containerId = containerExpiredEvent.getContainerId(); completedContainer(getRMContainer(containerId), SchedulerUtils.createAbnormalContainerStatus( containerId, SchedulerUtils.EXPIRED_CONTAINER), RMContainerEventType.EXPIRE); break; default: LOG.error("Unknown event arrived at FairScheduler: " + event.toString()); } } private synchronized String resolveReservationQueueName(String queueName, ApplicationId applicationId, ReservationId reservationID) { FSQueue queue = queueMgr.getQueue(queueName); if ((queue == null) || !allocConf.isReservable(queue.getQueueName())) { return queueName; } // Use fully specified name from now on (including root. prefix) queueName = queue.getQueueName(); if (reservationID != null) { String resQName = queueName + "." + reservationID.toString(); queue = queueMgr.getQueue(resQName); if (queue == null) { String message = "Application " + applicationId + " submitted to a reservation which is not yet currently active: " + resQName; this.rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return null; } if (!queue.getParent().getQueueName().equals(queueName)) { String message = "Application: " + applicationId + " submitted to a reservation " + resQName + " which does not belong to the specified queue: " + queueName; this.rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return null; } // use the reservation queue to run the app queueName = resQName; } else { // use the default child queue of the plan for unreserved apps queueName = getDefaultQueueForPlanQueue(queueName); } return queueName; } private String getDefaultQueueForPlanQueue(String queueName) { String planName = queueName.substring(queueName.lastIndexOf(".") + 1); queueName = queueName + "." + planName + ReservationConstants.DEFAULT_QUEUE_SUFFIX; return queueName; } @Override public void recover(RMState state) throws Exception { // NOT IMPLEMENTED } public synchronized void setRMContext(RMContext rmContext) { this.rmContext = rmContext; } private void initScheduler(Configuration conf) throws IOException { synchronized (this) { this.conf = new FairSchedulerConfiguration(conf); validateConf(this.conf); minimumAllocation = this.conf.getMinimumAllocation(); initMaximumResourceCapability(this.conf.getMaximumAllocation()); incrAllocation = this.conf.getIncrementAllocation(); continuousSchedulingEnabled = this.conf.isContinuousSchedulingEnabled(); continuousSchedulingSleepMs = this.conf.getContinuousSchedulingSleepMs(); nodeLocalityThreshold = this.conf.getLocalityThresholdNode(); rackLocalityThreshold = this.conf.getLocalityThresholdRack(); nodeLocalityDelayMs = this.conf.getLocalityDelayNodeMs(); rackLocalityDelayMs = this.conf.getLocalityDelayRackMs(); preemptionEnabled = this.conf.getPreemptionEnabled(); preemptionUtilizationThreshold = this.conf.getPreemptionUtilizationThreshold(); assignMultiple = this.conf.getAssignMultiple(); maxAssign = this.conf.getMaxAssign(); sizeBasedWeight = this.conf.getSizeBasedWeight(); preemptionInterval = this.conf.getPreemptionInterval(); waitTimeBeforeKill = this.conf.getWaitTimeBeforeKill(); usePortForNodeName = this.conf.getUsePortForNodeName(); updateInterval = this.conf.getUpdateInterval(); if (updateInterval < 0) { updateInterval = FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS; LOG.warn(FairSchedulerConfiguration.UPDATE_INTERVAL_MS + " is invalid, so using default value " + +FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS + " ms instead"); } rootMetrics = FSQueueMetrics.forQueue("root", null, true, conf); fsOpDurations = FSOpDurations.getInstance(true); // This stores per-application scheduling information this.applications = new ConcurrentHashMap< ApplicationId, SchedulerApplication<FSAppAttempt>>(); this.eventLog = new FairSchedulerEventLog(); eventLog.init(this.conf); allocConf = new AllocationConfiguration(conf); try { queueMgr.initialize(conf); } catch (Exception e) { throw new IOException("Failed to start FairScheduler", e); } updateThread = new UpdateThread(); updateThread.setName("FairSchedulerUpdateThread"); updateThread.setDaemon(true); if (continuousSchedulingEnabled) { // start continuous scheduling thread schedulingThread = new ContinuousSchedulingThread(); schedulingThread.setName("FairSchedulerContinuousScheduling"); schedulingThread.setDaemon(true); } } allocsLoader.init(conf); allocsLoader.setReloadListener(new AllocationReloadListener()); // If we fail to load allocations file on initialize, we want to fail // immediately. After a successful load, exceptions on future reloads // will just result in leaving things as they are. try { allocsLoader.reloadAllocations(); } catch (Exception e) { throw new IOException("Failed to initialize FairScheduler", e); } } private synchronized void startSchedulerThreads() { Preconditions.checkNotNull(updateThread, "updateThread is null"); Preconditions.checkNotNull(allocsLoader, "allocsLoader is null"); updateThread.start(); if (continuousSchedulingEnabled) { Preconditions.checkNotNull(schedulingThread, "schedulingThread is null"); schedulingThread.start(); } allocsLoader.start(); } @Override public void serviceInit(Configuration conf) throws Exception { initScheduler(conf); super.serviceInit(conf); } @Override public void serviceStart() throws Exception { startSchedulerThreads(); super.serviceStart(); } @Override public void serviceStop() throws Exception { synchronized (this) { if (updateThread != null) { updateThread.interrupt(); updateThread.join(THREAD_JOIN_TIMEOUT_MS); } if (continuousSchedulingEnabled) { if (schedulingThread != null) { schedulingThread.interrupt(); schedulingThread.join(THREAD_JOIN_TIMEOUT_MS); } } if (allocsLoader != null) { allocsLoader.stop(); } } super.serviceStop(); } @Override public void reinitialize(Configuration conf, RMContext rmContext) throws IOException { try { allocsLoader.reloadAllocations(); } catch (Exception e) { LOG.error("Failed to reload allocations file", e); } } @Override public QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive) throws IOException { if (!queueMgr.exists(queueName)) { throw new IOException("queue " + queueName + " does not exist"); } return queueMgr.getQueue(queueName).getQueueInfo(includeChildQueues, recursive); } @Override public List<QueueUserACLInfo> getQueueUserAclInfo() { UserGroupInformation user; try { user = UserGroupInformation.getCurrentUser(); } catch (IOException ioe) { return new ArrayList<QueueUserACLInfo>(); } return queueMgr.getRootQueue().getQueueUserAclInfo(user); } @Override public int getNumClusterNodes() { return nodes.size(); } @Override public synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName) { FSQueue queue = getQueueManager().getQueue(queueName); if (queue == null) { if (LOG.isDebugEnabled()) { LOG.debug("ACL not found for queue access-type " + acl + " for queue " + queueName); } return false; } return queue.hasAccess(acl, callerUGI); } public AllocationConfiguration getAllocationConfiguration() { return allocConf; } private class AllocationReloadListener implements AllocationFileLoaderService.Listener { @Override public void onReload(AllocationConfiguration queueInfo) { // Commit the reload; also create any queue defined in the alloc file // if it does not already exist, so it can be displayed on the web UI. synchronized (FairScheduler.this) { allocConf = queueInfo; allocConf.getDefaultSchedulingPolicy().initialize(clusterResource); queueMgr.updateAllocationConfiguration(allocConf); maxRunningEnforcer.updateRunnabilityOnReload(); } } } @Override public List<ApplicationAttemptId> getAppsInQueue(String queueName) { FSQueue queue = queueMgr.getQueue(queueName); if (queue == null) { return null; } List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>(); queue.collectSchedulerApplications(apps); return apps; } @Override public synchronized String moveApplication(ApplicationId appId, String queueName) throws YarnException { SchedulerApplication<FSAppAttempt> app = applications.get(appId); if (app == null) { throw new YarnException("App to be moved " + appId + " not found."); } FSAppAttempt attempt = (FSAppAttempt) app.getCurrentAppAttempt(); // To serialize with FairScheduler#allocate, synchronize on app attempt synchronized (attempt) { FSLeafQueue oldQueue = (FSLeafQueue) app.getQueue(); String destQueueName = handleMoveToPlanQueue(queueName); FSLeafQueue targetQueue = queueMgr.getLeafQueue(destQueueName, false); if (targetQueue == null) { throw new YarnException("Target queue " + queueName + " not found or is not a leaf queue."); } if (targetQueue == oldQueue) { return oldQueue.getQueueName(); } if (oldQueue.isRunnableApp(attempt)) { verifyMoveDoesNotViolateConstraints(attempt, oldQueue, targetQueue); } executeMove(app, attempt, oldQueue, targetQueue); return targetQueue.getQueueName(); } } private void verifyMoveDoesNotViolateConstraints(FSAppAttempt app, FSLeafQueue oldQueue, FSLeafQueue targetQueue) throws YarnException { String queueName = targetQueue.getQueueName(); ApplicationAttemptId appAttId = app.getApplicationAttemptId(); // When checking maxResources and maxRunningApps, only need to consider // queues before the lowest common ancestor of the two queues because the // total running apps in queues above will not be changed. FSQueue lowestCommonAncestor = findLowestCommonAncestorQueue(oldQueue, targetQueue); Resource consumption = app.getCurrentConsumption(); // Check whether the move would go over maxRunningApps or maxShare FSQueue cur = targetQueue; while (cur != lowestCommonAncestor) { // maxRunningApps if (cur.getNumRunnableApps() == allocConf.getQueueMaxApps(cur.getQueueName())) { throw new YarnException("Moving app attempt " + appAttId + " to queue " + queueName + " would violate queue maxRunningApps constraints on" + " queue " + cur.getQueueName()); } // maxShare if (!Resources.fitsIn(Resources.add(cur.getResourceUsage(), consumption), cur.getMaxShare())) { throw new YarnException("Moving app attempt " + appAttId + " to queue " + queueName + " would violate queue maxShare constraints on" + " queue " + cur.getQueueName()); } cur = cur.getParent(); } } /** * Helper for moveApplication, which has appropriate synchronization, so all * operations will be atomic. */ private void executeMove(SchedulerApplication<FSAppAttempt> app, FSAppAttempt attempt, FSLeafQueue oldQueue, FSLeafQueue newQueue) { boolean wasRunnable = oldQueue.removeApp(attempt); // if app was not runnable before, it may be runnable now boolean nowRunnable = maxRunningEnforcer.canAppBeRunnable(newQueue, attempt.getUser()); if (wasRunnable && !nowRunnable) { throw new IllegalStateException("Should have already verified that app " + attempt.getApplicationId() + " would be runnable in new queue"); } if (wasRunnable) { maxRunningEnforcer.untrackRunnableApp(attempt); } else if (nowRunnable) { // App has changed from non-runnable to runnable maxRunningEnforcer.untrackNonRunnableApp(attempt); } attempt.move(newQueue); // This updates all the metrics app.setQueue(newQueue); newQueue.addApp(attempt, nowRunnable); if (nowRunnable) { maxRunningEnforcer.trackRunnableApp(attempt); } if (wasRunnable) { maxRunningEnforcer.updateRunnabilityOnAppRemoval(attempt, oldQueue); } } @VisibleForTesting FSQueue findLowestCommonAncestorQueue(FSQueue queue1, FSQueue queue2) { // Because queue names include ancestors, separated by periods, we can find // the lowest common ancestors by going from the start of the names until // there's a character that doesn't match. String name1 = queue1.getName(); String name2 = queue2.getName(); // We keep track of the last period we encounter to avoid returning root.apple // when the queues are root.applepie and root.appletart int lastPeriodIndex = -1; for (int i = 0; i < Math.max(name1.length(), name2.length()); i++) { if (name1.length() <= i || name2.length() <= i || name1.charAt(i) != name2.charAt(i)) { return queueMgr.getQueue(name1.substring(0, lastPeriodIndex)); } else if (name1.charAt(i) == '.') { lastPeriodIndex = i; } } return queue1; // names are identical } /** * Process resource update on a node and update Queue. */ @Override public synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption) { super.updateNodeResource(nm, resourceOption); updateRootQueueMetrics(); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); } /** {@inheritDoc} */ @Override public EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes() { return EnumSet .of(SchedulerResourceTypes.MEMORY, SchedulerResourceTypes.CPU); } @Override public Set<String> getPlanQueues() throws YarnException { Set<String> planQueues = new HashSet<String>(); for (FSQueue fsQueue : queueMgr.getQueues()) { String queueName = fsQueue.getName(); if (allocConf.isReservable(queueName)) { planQueues.add(queueName); } } return planQueues; } @Override public void setEntitlement(String queueName, QueueEntitlement entitlement) throws YarnException { FSLeafQueue reservationQueue = queueMgr.getLeafQueue(queueName, false); if (reservationQueue == null) { throw new YarnException("Target queue " + queueName + " not found or is not a leaf queue."); } reservationQueue.setWeights(entitlement.getCapacity()); // TODO Does MaxCapacity need to be set for fairScheduler ? } /** * Only supports removing empty leaf queues * @param queueName name of queue to remove * @throws YarnException if queue to remove is either not a leaf or if its * not empty */ @Override public void removeQueue(String queueName) throws YarnException { FSLeafQueue reservationQueue = queueMgr.getLeafQueue(queueName, false); if (reservationQueue != null) { if (!queueMgr.removeLeafQueue(queueName)) { throw new YarnException("Could not remove queue " + queueName + " as " + "its either not a leaf queue or its not empty"); } } } private String handleMoveToPlanQueue(String targetQueueName) { FSQueue dest = queueMgr.getQueue(targetQueueName); if (dest != null && allocConf.isReservable(dest.getQueueName())) { // use the default child reservation queue of the plan targetQueueName = getDefaultQueueForPlanQueue(targetQueueName); } return targetQueueName; } /* Start-Wajih Get decision stats*/ @Override public String getDecisionTimeStats() { int max_time=0; int min_time=0; // Break down the decision time space into 4 spaces; long part_0_5=0; long part_5_10=0; long part_10_25=0; long part_25_inf=0; String dec_string=" "; boolean flag=true; System.out.println("No of decisions are = " + no_of_decisions); for(int i=0 ; i<10000; i++){ if(i>0 && i<=5) part_0_5+=decision_time[i]; if(i>5 && i<=10) part_5_10+=decision_time[i]; if(i>10 && i<=25) part_10_25+=decision_time[i]; if(i>25) part_25_inf+=decision_time[i]; if(flag && decision_time[i] >=1){ min_time=i; flag=false; } if(decision_time[i] >=1){ max_time=i; } dec_string+="Max Time : "; dec_string+=max_time; dec_string+=" ---- "; dec_string+="Min Time : "; dec_string+=min_time; dec_string+="\n"; dec_string+="Percentage of decision timings in between 0-5 Millisecond = "; dec_string+=((part_0_5*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings in between 5-10 Millisecond = "; dec_string+=((part_5_10*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings in between 10-25 Millisecond = "; dec_string+=((part_10_25*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings >25 Millisecond = "; dec_string+=((part_10_25*1.0)/no_of_decisions)*100; } return dec_string; /* String decision_str=""; long tmp_sum=0; long tmp_sum2=0; for(int i=0;i<=5;i++) tmp_sum+=decisionArray[i]; decision_str+=" 0-5: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=6;i<=10;i++) tmp_sum+=decisionArray[i]; decision_str+=" 5-10: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=11;i<=25;i++) tmp_sum+=decisionArray[i]; decision_str+=" 10-25: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=26;i<=50;i++) tmp_sum+=decisionArray[i]; decision_str+=" 25-50: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; return decision_str; */ } /* END -wajih*/ }
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServiceProtos.SchedulerResourceTypes; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationConstants; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppRejectedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt.ContainersAndNMTokensAllocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.QueueEntitlement; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerExpiredSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeResourceUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * A scheduler that schedules resources between a set of queues. The scheduler * keeps track of the resources used by each queue, and attempts to maintain * fairness by scheduling tasks at queues whose allocations are farthest below * an ideal fair distribution. * * The fair scheduler supports hierarchical queues. All queues descend from a * queue named "root". Available resources are distributed among the children * of the root queue in the typical fair scheduling fashion. Then, the children * distribute the resources assigned to them to their children in the same * fashion. Applications may only be scheduled on leaf queues. Queues can be * specified as children of other queues by placing them as sub-elements of their * parents in the fair scheduler configuration file. * * A queue's name starts with the names of its parents, with periods as * separators. So a queue named "queue1" under the root named, would be * referred to as "root.queue1", and a queue named "queue2" under a queue * named "parent1" would be referred to as "root.parent1.queue2". */ @LimitedPrivate("yarn") @Unstable @SuppressWarnings("unchecked") public class FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { private FairSchedulerConfiguration conf; private Resource incrAllocation; private QueueManager queueMgr; private volatile Clock clock; private boolean usePortForNodeName; private static final Log LOG = LogFactory.getLog(FairScheduler.class); private static final ResourceCalculator RESOURCE_CALCULATOR = new DefaultResourceCalculator(); private static final ResourceCalculator DOMINANT_RESOURCE_CALCULATOR = new DominantResourceCalculator(); // Value that container assignment methods return when a container is // reserved public static final Resource CONTAINER_RESERVED = Resources.createResource(-1); // How often fair shares are re-calculated (ms) protected long updateInterval; private final int UPDATE_DEBUG_FREQUENCY = 5; private int updatesToSkipForDebug = UPDATE_DEBUG_FREQUENCY; @VisibleForTesting Thread updateThread; @VisibleForTesting Thread schedulingThread; // timeout to join when we stop this service protected final long THREAD_JOIN_TIMEOUT_MS = 1000; // Aggregate metrics FSQueueMetrics rootMetrics; FSOpDurations fsOpDurations; // Time when we last updated preemption vars protected long lastPreemptionUpdateTime; // Time we last ran preemptTasksIfNecessary private long lastPreemptCheckTime; // Preemption related variables protected boolean preemptionEnabled; protected float preemptionUtilizationThreshold; // How often tasks are preempted protected long preemptionInterval; // ms to wait before force killing stuff (must be longer than a couple // of heartbeats to give task-kill commands a chance to act). protected long waitTimeBeforeKill; // Containers whose AMs have been warned that they will be preempted soon. private List<RMContainer> warnedContainers = new ArrayList<RMContainer>(); protected boolean sizeBasedWeight; // Give larger weights to larger jobs protected WeightAdjuster weightAdjuster; // Can be null for no weight adjuster protected boolean continuousSchedulingEnabled; // Continuous Scheduling enabled or not protected int continuousSchedulingSleepMs; // Sleep time for each pass in continuous scheduling private Comparator<NodeId> nodeAvailableResourceComparator = new NodeAvailableResourceComparator(); // Node available resource comparator protected double nodeLocalityThreshold; // Cluster threshold for node locality protected double rackLocalityThreshold; // Cluster threshold for rack locality protected long nodeLocalityDelayMs; // Delay for node locality protected long rackLocalityDelayMs; // Delay for rack locality private FairSchedulerEventLog eventLog; // Machine-readable event log protected boolean assignMultiple; // Allocate multiple containers per // heartbeat protected int maxAssign; // Max containers to assign per heartbeat /* Start -Wajih Measuring decision timings*/ public int dec_array_size=10000; public int[] decision_time; public long no_of_decisions; /* End - Wajih*/ @VisibleForTesting final MaxRunningAppsEnforcer maxRunningEnforcer; private AllocationFileLoaderService allocsLoader; @VisibleForTesting AllocationConfiguration allocConf; public FairScheduler() { super(FairScheduler.class.getName()); clock = new SystemClock(); allocsLoader = new AllocationFileLoaderService(); queueMgr = new QueueManager(this); maxRunningEnforcer = new MaxRunningAppsEnforcer(this); /*Start Wajih Measuring decision timings*/ dec_array_size=10000; decision_time = new int[dec_array_size]; /* End Wajih */ } private void validateConf(Configuration conf) { // validate scheduler memory allocation setting int minMem = conf.getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); int maxMem = conf.getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB); if (minMem < 0 || minMem > maxMem) { throw new YarnRuntimeException("Invalid resource scheduler memory" + " allocation configuration" + ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB + "=" + minMem + ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + "=" + maxMem + ", min should equal greater than 0" + ", max should be no smaller than min."); } // validate scheduler vcores allocation setting int minVcores = conf.getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); int maxVcores = conf.getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); if (minVcores < 0 || minVcores > maxVcores) { throw new YarnRuntimeException("Invalid resource scheduler vcores" + " allocation configuration" + ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES + "=" + minVcores + ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES + "=" + maxVcores + ", min should equal greater than 0" + ", max should be no smaller than min."); } } public FairSchedulerConfiguration getConf() { return conf; } public QueueManager getQueueManager() { return queueMgr; } /** * Thread which calls {@link FairScheduler#update()} every * <code>updateInterval</code> milliseconds. */ private class UpdateThread extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(updateInterval); long start = getClock().getTime(); update(); preemptTasksIfNecessary(); long duration = getClock().getTime() - start; fsOpDurations.addUpdateThreadRunDuration(duration); } catch (InterruptedException ie) { LOG.warn("Update thread interrupted. Exiting."); return; } catch (Exception e) { LOG.error("Exception in fair scheduler UpdateThread", e); } } } } /** * Thread which attempts scheduling resources continuously, * asynchronous to the node heartbeats. */ private class ContinuousSchedulingThread extends Thread { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { continuousSchedulingAttempt(); Thread.sleep(getContinuousSchedulingSleepMs()); } catch (InterruptedException e) { LOG.warn("Continuous scheduling thread interrupted. Exiting.", e); return; } } } } /** * Recompute the internal variables used by the scheduler - per-job weights, * fair shares, deficits, minimum slot allocations, and amount of used and * required resources per job. */ protected synchronized void update() { long start = getClock().getTime(); updateStarvationStats(); // Determine if any queues merit preemption FSQueue rootQueue = queueMgr.getRootQueue(); // Recursively update demands for all queues rootQueue.updateDemand(); rootQueue.setFairShare(clusterResource); // Recursively compute fair shares for all queues // and update metrics rootQueue.recomputeShares(); updateRootQueueMetrics(); if (LOG.isDebugEnabled()) { if (--updatesToSkipForDebug < 0) { updatesToSkipForDebug = UPDATE_DEBUG_FREQUENCY; LOG.debug("Cluster Capacity: " + clusterResource + " Allocations: " + rootMetrics.getAllocatedResources() + " Availability: " + Resource.newInstance( rootMetrics.getAvailableMB(), rootMetrics.getAvailableVirtualCores()) + " Demand: " + rootQueue.getDemand()); } } long duration = getClock().getTime() - start; fsOpDurations.addUpdateCallDuration(duration); } /** * Update the preemption fields for all QueueScheduables, i.e. the times since * each queue last was at its guaranteed share and over its fair share * threshold for each type of task. */ private void updateStarvationStats() { lastPreemptionUpdateTime = clock.getTime(); for (FSLeafQueue sched : queueMgr.getLeafQueues()) { sched.updateStarvationStats(); } } /** * Check for queues that need tasks preempted, either because they have been * below their guaranteed share for minSharePreemptionTimeout or they have * been below their fair share threshold for the fairSharePreemptionTimeout. If * such queues exist, compute how many tasks of each type need to be preempted * and then select the right ones using preemptTasks. */ protected synchronized void preemptTasksIfNecessary() { if (!shouldAttemptPreemption()) { return; } long curTime = getClock().getTime(); if (curTime - lastPreemptCheckTime < preemptionInterval) { return; } lastPreemptCheckTime = curTime; Resource resToPreempt = Resources.clone(Resources.none()); for (FSLeafQueue sched : queueMgr.getLeafQueues()) { Resources.addTo(resToPreempt, resToPreempt(sched, curTime)); } if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, resToPreempt, Resources.none())) { preemptResources(resToPreempt); } } /** * Preempt a quantity of resources. Each round, we start from the root queue, * level-by-level, until choosing a candidate application. * The policy for prioritizing preemption for each queue depends on its * SchedulingPolicy: (1) fairshare/DRF, choose the ChildSchedulable that is * most over its fair share; (2) FIFO, choose the childSchedulable that is * latest launched. * Inside each application, we further prioritize preemption by choosing * containers with lowest priority to preempt. * We make sure that no queue is placed below its fair share in the process. */ protected void preemptResources(Resource toPreempt) { long start = getClock().getTime(); if (Resources.equals(toPreempt, Resources.none())) { return; } // Scan down the list of containers we've already warned and kill them // if we need to. Remove any containers from the list that we don't need // or that are no longer running. Iterator<RMContainer> warnedIter = warnedContainers.iterator(); while (warnedIter.hasNext()) { RMContainer container = warnedIter.next(); if ((container.getState() == RMContainerState.RUNNING || container.getState() == RMContainerState.ALLOCATED) && Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, toPreempt, Resources.none())) { warnOrKillContainer(container); Resources.subtractFrom(toPreempt, container.getContainer().getResource()); } else { warnedIter.remove(); } } try { // Reset preemptedResource for each app for (FSLeafQueue queue : getQueueManager().getLeafQueues()) { queue.resetPreemptedResources(); } while (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, toPreempt, Resources.none())) { RMContainer container = getQueueManager().getRootQueue().preemptContainer(); if (container == null) { break; } else { warnOrKillContainer(container); warnedContainers.add(container); Resources.subtractFrom( toPreempt, container.getContainer().getResource()); } } } finally { // Clear preemptedResources for each app for (FSLeafQueue queue : getQueueManager().getLeafQueues()) { queue.clearPreemptedResources(); } } long duration = getClock().getTime() - start; fsOpDurations.addPreemptCallDuration(duration); } protected void warnOrKillContainer(RMContainer container) { ApplicationAttemptId appAttemptId = container.getApplicationAttemptId(); FSAppAttempt app = getSchedulerApp(appAttemptId); FSLeafQueue queue = app.getQueue(); LOG.info("Preempting container (prio=" + container.getContainer().getPriority() + "res=" + container.getContainer().getResource() + ") from queue " + queue.getName()); Long time = app.getContainerPreemptionTime(container); if (time != null) { // if we asked for preemption more than maxWaitTimeBeforeKill ms ago, // proceed with kill if (time + waitTimeBeforeKill < getClock().getTime()) { ContainerStatus status = SchedulerUtils.createPreemptedContainerStatus( container.getContainerId(), SchedulerUtils.PREEMPTED_CONTAINER); recoverResourceRequestForContainer(container); // TODO: Not sure if this ever actually adds this to the list of cleanup // containers on the RMNode (see SchedulerNode.releaseContainer()). completedContainer(container, status, RMContainerEventType.KILL); LOG.info("Killing container" + container + " (after waiting for premption for " + (getClock().getTime() - time) + "ms)"); } } else { // track the request in the FSAppAttempt itself app.addPreemption(container, getClock().getTime()); } } /** * Return the resource amount that this queue is allowed to preempt, if any. * If the queue has been below its min share for at least its preemption * timeout, it should preempt the difference between its current share and * this min share. If it has been below its fair share preemption threshold * for at least the fairSharePreemptionTimeout, it should preempt enough tasks * to get up to its full fair share. If both conditions hold, we preempt the * max of the two amounts (this shouldn't happen unless someone sets the * timeouts to be identical for some reason). */ protected Resource resToPreempt(FSLeafQueue sched, long curTime) { long minShareTimeout = sched.getMinSharePreemptionTimeout(); long fairShareTimeout = sched.getFairSharePreemptionTimeout(); Resource resDueToMinShare = Resources.none(); Resource resDueToFairShare = Resources.none(); if (curTime - sched.getLastTimeAtMinShare() > minShareTimeout) { Resource target = Resources.min(RESOURCE_CALCULATOR, clusterResource, sched.getMinShare(), sched.getDemand()); resDueToMinShare = Resources.max(RESOURCE_CALCULATOR, clusterResource, Resources.none(), Resources.subtract(target, sched.getResourceUsage())); } if (curTime - sched.getLastTimeAtFairShareThreshold() > fairShareTimeout) { Resource target = Resources.min(RESOURCE_CALCULATOR, clusterResource, sched.getFairShare(), sched.getDemand()); resDueToFairShare = Resources.max(RESOURCE_CALCULATOR, clusterResource, Resources.none(), Resources.subtract(target, sched.getResourceUsage())); } Resource resToPreempt = Resources.max(RESOURCE_CALCULATOR, clusterResource, resDueToMinShare, resDueToFairShare); if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, resToPreempt, Resources.none())) { String message = "Should preempt " + resToPreempt + " res for queue " + sched.getName() + ": resDueToMinShare = " + resDueToMinShare + ", resDueToFairShare = " + resDueToFairShare; LOG.info(message); } return resToPreempt; } public synchronized RMContainerTokenSecretManager getContainerTokenSecretManager() { return rmContext.getContainerTokenSecretManager(); } // synchronized for sizeBasedWeight public synchronized ResourceWeights getAppWeight(FSAppAttempt app) { double weight = 1.0; if (sizeBasedWeight) { // Set weight based on current memory demand weight = Math.log1p(app.getDemand().getMemory()) / Math.log(2); } weight *= app.getPriority().getPriority(); if (weightAdjuster != null) { // Run weight through the user-supplied weightAdjuster weight = weightAdjuster.adjustWeight(app, weight); } ResourceWeights resourceWeights = app.getResourceWeights(); resourceWeights.setWeight((float)weight); return resourceWeights; } public Resource getIncrementResourceCapability() { return incrAllocation; } private FSSchedulerNode getFSSchedulerNode(NodeId nodeId) { return nodes.get(nodeId); } public double getNodeLocalityThreshold() { return nodeLocalityThreshold; } public double getRackLocalityThreshold() { return rackLocalityThreshold; } public long getNodeLocalityDelayMs() { return nodeLocalityDelayMs; } public long getRackLocalityDelayMs() { return rackLocalityDelayMs; } public boolean isContinuousSchedulingEnabled() { return continuousSchedulingEnabled; } public synchronized int getContinuousSchedulingSleepMs() { return continuousSchedulingSleepMs; } public Clock getClock() { return clock; } @VisibleForTesting void setClock(Clock clock) { this.clock = clock; } public FairSchedulerEventLog getEventLog() { return eventLog; } /** * Add a new application to the scheduler, with a given id, queue name, and * user. This will accept a new app even if the user or queue is above * configured limits, but the app will not be marked as runnable. */ protected synchronized void addApplication(ApplicationId applicationId, String queueName, String user, boolean isAppRecovering) { if (queueName == null || queueName.isEmpty()) { String message = "Reject application " + applicationId + " submitted by user " + user + " with an empty queue name."; LOG.info(message); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return; } if (queueName.startsWith(".") || queueName.endsWith(".")) { String message = "Reject application " + applicationId + " submitted by user " + user + " with an illegal queue name " + queueName + ". " + "The queue name cannot start/end with period."; LOG.info(message); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return; } RMApp rmApp = rmContext.getRMApps().get(applicationId); FSLeafQueue queue = assignToQueue(rmApp, queueName, user); if (queue == null) { return; } // Enforce ACLs UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(user); if (!queue.hasAccess(QueueACL.SUBMIT_APPLICATIONS, userUgi) && !queue.hasAccess(QueueACL.ADMINISTER_QUEUE, userUgi)) { String msg = "User " + userUgi.getUserName() + " cannot submit applications to queue " + queue.getName(); LOG.info(msg); rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, msg)); return; } SchedulerApplication<FSAppAttempt> application = new SchedulerApplication<FSAppAttempt>(queue, user); applications.put(applicationId, application); queue.getMetrics().submitApp(user); LOG.info("Accepted application " + applicationId + " from user: " + user + ", in queue: " + queueName + ", currently num of applications: " + applications.size()); if (isAppRecovering) { if (LOG.isDebugEnabled()) { LOG.debug(applicationId + " is recovering. Skip notifying APP_ACCEPTED"); } } else { rmContext.getDispatcher().getEventHandler() .handle(new RMAppEvent(applicationId, RMAppEventType.APP_ACCEPTED)); } } /** * Add a new application attempt to the scheduler. */ protected synchronized void addApplicationAttempt( ApplicationAttemptId applicationAttemptId, boolean transferStateFromPreviousAttempt, boolean isAttemptRecovering) { SchedulerApplication<FSAppAttempt> application = applications.get(applicationAttemptId.getApplicationId()); String user = application.getUser(); FSLeafQueue queue = (FSLeafQueue) application.getQueue(); FSAppAttempt attempt = new FSAppAttempt(this, applicationAttemptId, user, queue, new ActiveUsersManager(getRootQueueMetrics()), rmContext); if (transferStateFromPreviousAttempt) { attempt.transferStateFromPreviousAttempt(application .getCurrentAppAttempt()); } application.setCurrentAppAttempt(attempt); boolean runnable = maxRunningEnforcer.canAppBeRunnable(queue, user); queue.addApp(attempt, runnable); if (runnable) { maxRunningEnforcer.trackRunnableApp(attempt); } else { maxRunningEnforcer.trackNonRunnableApp(attempt); } queue.getMetrics().submitAppAttempt(user); LOG.info("Added Application Attempt " + applicationAttemptId + " to scheduler from user: " + user); if (isAttemptRecovering) { if (LOG.isDebugEnabled()) { LOG.debug(applicationAttemptId + " is recovering. Skipping notifying ATTEMPT_ADDED"); } } else { rmContext.getDispatcher().getEventHandler().handle( new RMAppAttemptEvent(applicationAttemptId, RMAppAttemptEventType.ATTEMPT_ADDED)); } } /** * Helper method that attempts to assign the app to a queue. The method is * responsible to call the appropriate event-handler if the app is rejected. */ @VisibleForTesting FSLeafQueue assignToQueue(RMApp rmApp, String queueName, String user) { FSLeafQueue queue = null; String appRejectMsg = null; try { QueuePlacementPolicy placementPolicy = allocConf.getPlacementPolicy(); queueName = placementPolicy.assignAppToQueue(queueName, user); if (queueName == null) { appRejectMsg = "Application rejected by queue placement policy"; } else { queue = queueMgr.getLeafQueue(queueName, true); if (queue == null) { appRejectMsg = queueName + " is not a leaf queue"; } } } catch (IOException ioe) { appRejectMsg = "Error assigning app to queue " + queueName; } if (appRejectMsg != null && rmApp != null) { LOG.error(appRejectMsg); rmContext.getDispatcher().getEventHandler().handle( new RMAppRejectedEvent(rmApp.getApplicationId(), appRejectMsg)); return null; } if (rmApp != null) { rmApp.setQueue(queue.getName()); } else { LOG.error("Couldn't find RM app to set queue name on"); } return queue; } private synchronized void removeApplication(ApplicationId applicationId, RMAppState finalState) { SchedulerApplication<FSAppAttempt> application = applications.get(applicationId); if (application == null){ LOG.warn("Couldn't find application " + applicationId); return; } application.stop(finalState); applications.remove(applicationId); } private synchronized void removeApplicationAttempt( ApplicationAttemptId applicationAttemptId, RMAppAttemptState rmAppAttemptFinalState, boolean keepContainers) { LOG.info("Application " + applicationAttemptId + " is done." + " finalState=" + rmAppAttemptFinalState); SchedulerApplication<FSAppAttempt> application = applications.get(applicationAttemptId.getApplicationId()); FSAppAttempt attempt = getSchedulerApp(applicationAttemptId); if (attempt == null || application == null) { LOG.info("Unknown application " + applicationAttemptId + " has completed!"); return; } // Release all the running containers for (RMContainer rmContainer : attempt.getLiveContainers()) { if (keepContainers && rmContainer.getState().equals(RMContainerState.RUNNING)) { // do not kill the running container in the case of work-preserving AM // restart. LOG.info("Skip killing " + rmContainer.getContainerId()); continue; } completedContainer(rmContainer, SchedulerUtils.createAbnormalContainerStatus( rmContainer.getContainerId(), SchedulerUtils.COMPLETED_APPLICATION), RMContainerEventType.KILL); } // Release all reserved containers for (RMContainer rmContainer : attempt.getReservedContainers()) { completedContainer(rmContainer, SchedulerUtils.createAbnormalContainerStatus( rmContainer.getContainerId(), "Application Complete"), RMContainerEventType.KILL); } // Clean up pending requests, metrics etc. attempt.stop(rmAppAttemptFinalState); // Inform the queue FSLeafQueue queue = queueMgr.getLeafQueue(attempt.getQueue() .getQueueName(), false); boolean wasRunnable = queue.removeApp(attempt); if (wasRunnable) { maxRunningEnforcer.untrackRunnableApp(attempt); maxRunningEnforcer.updateRunnabilityOnAppRemoval(attempt, attempt.getQueue()); } else { maxRunningEnforcer.untrackNonRunnableApp(attempt); } } /** * Clean up a completed container. */ @Override protected synchronized void completedContainer(RMContainer rmContainer, ContainerStatus containerStatus, RMContainerEventType event) { if (rmContainer == null) { LOG.info("Null container completed..."); return; } Container container = rmContainer.getContainer(); // Get the application for the finished container FSAppAttempt application = getCurrentAttemptForContainer(container.getId()); ApplicationId appId = container.getId().getApplicationAttemptId().getApplicationId(); if (application == null) { LOG.info("Container " + container + " of" + " unknown application attempt " + appId + " completed with event " + event); return; } // Get the node on which the container was allocated FSSchedulerNode node = getFSSchedulerNode(container.getNodeId()); if (rmContainer.getState() == RMContainerState.RESERVED) { application.unreserve(rmContainer.getReservedPriority(), node); } else { application.containerCompleted(rmContainer, containerStatus, event); node.releaseContainer(container); updateRootQueueMetrics(); } LOG.info("Application attempt " + application.getApplicationAttemptId() + " released container " + container.getId() + " on node: " + node + " with event: " + event); } private synchronized void addNode(RMNode node) { FSSchedulerNode schedulerNode = new FSSchedulerNode(node, usePortForNodeName); nodes.put(node.getNodeID(), schedulerNode); Resources.addTo(clusterResource, node.getTotalCapability()); updateRootQueueMetrics(); updateMaximumAllocation(schedulerNode, true); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); LOG.info("Added node " + node.getNodeAddress() + " cluster capacity: " + clusterResource); } private synchronized void removeNode(RMNode rmNode) { FSSchedulerNode node = getFSSchedulerNode(rmNode.getNodeID()); // This can occur when an UNHEALTHY node reconnects if (node == null) { return; } Resources.subtractFrom(clusterResource, rmNode.getTotalCapability()); updateRootQueueMetrics(); // Remove running containers List<RMContainer> runningContainers = node.getRunningContainers(); for (RMContainer container : runningContainers) { completedContainer(container, SchedulerUtils.createAbnormalContainerStatus( container.getContainerId(), SchedulerUtils.LOST_CONTAINER), RMContainerEventType.KILL); } // Remove reservations, if any RMContainer reservedContainer = node.getReservedContainer(); if (reservedContainer != null) { completedContainer(reservedContainer, SchedulerUtils.createAbnormalContainerStatus( reservedContainer.getContainerId(), SchedulerUtils.LOST_CONTAINER), RMContainerEventType.KILL); } nodes.remove(rmNode.getNodeID()); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); updateMaximumAllocation(node, false); LOG.info("Removed node " + rmNode.getNodeAddress() + " cluster capacity: " + clusterResource); } @Override public Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals) { // Make sure this application exists FSAppAttempt application = getSchedulerApp(appAttemptId); if (application == null) { LOG.info("Calling allocate on removed " + "or non existant application " + appAttemptId); return EMPTY_ALLOCATION; } // Sanity check SchedulerUtils.normalizeRequests(ask, DOMINANT_RESOURCE_CALCULATOR, clusterResource, minimumAllocation, getMaximumResourceCapability(), incrAllocation); // Set amResource for this app if (!application.getUnmanagedAM() && ask.size() == 1 && application.getLiveContainers().isEmpty()) { application.setAMResource(ask.get(0).getCapability()); } // Release containers releaseContainers(release, application); synchronized (application) { if (!ask.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("allocate: pre-update" + " applicationAttemptId=" + appAttemptId + " application=" + application.getApplicationId()); } application.showRequests(); // Update application requests application.updateResourceRequests(ask); application.showRequests(); } if (LOG.isDebugEnabled()) { LOG.debug("allocate: post-update" + " applicationAttemptId=" + appAttemptId + " #ask=" + ask.size() + " reservation= " + application.getCurrentReservation()); LOG.debug("Preempting " + application.getPreemptionContainers().size() + " container(s)"); } Set<ContainerId> preemptionContainerIds = new HashSet<ContainerId>(); for (RMContainer container : application.getPreemptionContainers()) { preemptionContainerIds.add(container.getContainerId()); } application.updateBlacklist(blacklistAdditions, blacklistRemovals); ContainersAndNMTokensAllocation allocation = application.pullNewlyAllocatedContainersAndNMTokens(); Resource headroom = application.getHeadroom(); application.setApplicationHeadroomForMetrics(headroom); return new Allocation(allocation.getContainerList(), headroom, preemptionContainerIds, null, null, allocation.getNMTokenList()); } } /** * Process a heartbeat update from a node. */ private synchronized void nodeUpdate(RMNode nm) { long start = getClock().getTime(); if (LOG.isDebugEnabled()) { LOG.debug("nodeUpdate: " + nm + " cluster capacity: " + clusterResource); } eventLog.log("HEARTBEAT", nm.getHostName()); FSSchedulerNode node = getFSSchedulerNode(nm.getNodeID()); List<UpdatedContainerInfo> containerInfoList = nm.pullContainerUpdates(); List<ContainerStatus> newlyLaunchedContainers = new ArrayList<ContainerStatus>(); List<ContainerStatus> completedContainers = new ArrayList<ContainerStatus>(); for(UpdatedContainerInfo containerInfo : containerInfoList) { newlyLaunchedContainers.addAll(containerInfo.getNewlyLaunchedContainers()); completedContainers.addAll(containerInfo.getCompletedContainers()); } // Processing the newly launched containers for (ContainerStatus launchedContainer : newlyLaunchedContainers) { containerLaunchedOnNode(launchedContainer.getContainerId(), node); } // Process completed containers for (ContainerStatus completedContainer : completedContainers) { ContainerId containerId = completedContainer.getContainerId(); LOG.debug("Container FINISHED: " + containerId); completedContainer(getRMContainer(containerId), completedContainer, RMContainerEventType.FINISHED); } /* Start Wajih Adding Timers to check decision delays*/ no_of_decisions++; /* End */ if (continuousSchedulingEnabled) { if (!completedContainers.isEmpty()) { attemptScheduling(node); } } else { /* Start Wajih Adding Timers to check decision delays*/ long beforeTime = System.currentTimeMillis(); /* End */ attemptScheduling(node); /* Start Wajih Adding Timers to check decision delays*/ long afterTime = System.currentTimeMillis(); int dec_time = (int)(afterTime-beforeTime); decision_time[dec_time]++; /* End */ } long duration = getClock().getTime() - start; fsOpDurations.addNodeUpdateDuration(duration); } void continuousSchedulingAttempt() throws InterruptedException { long start = getClock().getTime(); List<NodeId> nodeIdList = new ArrayList<NodeId>(nodes.keySet()); // Sort the nodes by space available on them, so that we offer // containers on emptier nodes first, facilitating an even spread. This // requires holding the scheduler lock, so that the space available on a // node doesn't change during the sort. synchronized (this) { Collections.sort(nodeIdList, nodeAvailableResourceComparator); } // iterate all nodes for (NodeId nodeId : nodeIdList) { FSSchedulerNode node = getFSSchedulerNode(nodeId); try { if (node != null && Resources.fitsIn(minimumAllocation, node.getAvailableResource())) { attemptScheduling(node); } } catch (Throwable ex) { LOG.error("Error while attempting scheduling for node " + node + ": " + ex.toString(), ex); } } long duration = getClock().getTime() - start; fsOpDurations.addContinuousSchedulingRunDuration(duration); } /** Sort nodes by available resource */ private class NodeAvailableResourceComparator implements Comparator<NodeId> { @Override public int compare(NodeId n1, NodeId n2) { if (!nodes.containsKey(n1)) { return 1; } if (!nodes.containsKey(n2)) { return -1; } return RESOURCE_CALCULATOR.compare(clusterResource, nodes.get(n2).getAvailableResource(), nodes.get(n1).getAvailableResource()); } } private synchronized void attemptScheduling(FSSchedulerNode node) { if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext.isSchedulerReadyForAllocatingContainers()) { return; } // Assign new containers... // 1. Check for reserved applications // 2. Schedule if there are no reservations FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); if (reservedAppSchedulable != null) { Priority reservedPriority = node.getReservedContainer().getReservedPriority(); FSQueue queue = reservedAppSchedulable.getQueue(); if (!reservedAppSchedulable.hasContainerForNode(reservedPriority, node) || !fitsInMaxShare(queue, node.getReservedContainer().getReservedResource())) { // Don't hold the reservation if app can no longer use it LOG.info("Releasing reservation that cannot be satisfied for application " + reservedAppSchedulable.getApplicationAttemptId() + " on node " + node); reservedAppSchedulable.unreserve(reservedPriority, node); reservedAppSchedulable = null; } else { // Reservation exists; try to fulfill the reservation if (LOG.isDebugEnabled()) { LOG.debug("Trying to fulfill reservation for application " + reservedAppSchedulable.getApplicationAttemptId() + " on node: " + node); } node.getReservedAppSchedulable().assignReservedContainer(node); } } if (reservedAppSchedulable == null) { // No reservation, schedule at queue which is farthest below fair share int assignedContainers = 0; while (node.getReservedContainer() == null) { boolean assignedContainer = false; if (!queueMgr.getRootQueue().assignContainer(node).equals( Resources.none())) { assignedContainers++; assignedContainer = true; } if (!assignedContainer) { break; } if (!assignMultiple) { break; } if ((assignedContainers >= maxAssign) && (maxAssign > 0)) { break; } } } updateRootQueueMetrics(); } static boolean fitsInMaxShare(FSQueue queue, Resource additionalResource) { Resource usagePlusAddition = Resources.add(queue.getResourceUsage(), additionalResource); if (!Resources.fitsIn(usagePlusAddition, queue.getMaxShare())) { return false; } FSQueue parentQueue = queue.getParent(); if (parentQueue != null) { return fitsInMaxShare(parentQueue, additionalResource); } return true; } public FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId) { return super.getApplicationAttempt(appAttemptId); } @Override public ResourceCalculator getResourceCalculator() { return RESOURCE_CALCULATOR; } /** * Subqueue metrics might be a little out of date because fair shares are * recalculated at the update interval, but the root queue metrics needs to * be updated synchronously with allocations and completions so that cluster * metrics will be consistent. */ private void updateRootQueueMetrics() { rootMetrics.setAvailableResourcesToQueue( Resources.subtract( clusterResource, rootMetrics.getAllocatedResources())); } /** * Check if preemption is enabled and the utilization threshold for * preemption is met. * * @return true if preemption should be attempted, false otherwise. */ private boolean shouldAttemptPreemption() { if (preemptionEnabled) { return (preemptionUtilizationThreshold < Math.max( (float) rootMetrics.getAllocatedMB() / clusterResource.getMemory(), (float) rootMetrics.getAllocatedVirtualCores() / clusterResource.getVirtualCores())); } return false; } @Override public QueueMetrics getRootQueueMetrics() { return rootMetrics; } @Override public void handle(SchedulerEvent event) { switch (event.getType()) { case NODE_ADDED: if (!(event instanceof NodeAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent)event; addNode(nodeAddedEvent.getAddedRMNode()); recoverContainersOnNode(nodeAddedEvent.getContainerReports(), nodeAddedEvent.getAddedRMNode()); break; case NODE_REMOVED: if (!(event instanceof NodeRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent)event; removeNode(nodeRemovedEvent.getRemovedRMNode()); break; case NODE_UPDATE: if (!(event instanceof NodeUpdateSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeUpdateSchedulerEvent nodeUpdatedEvent = (NodeUpdateSchedulerEvent)event; nodeUpdate(nodeUpdatedEvent.getRMNode()); break; case APP_ADDED: if (!(event instanceof AppAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent) event; String queueName = resolveReservationQueueName(appAddedEvent.getQueue(), appAddedEvent.getApplicationId(), appAddedEvent.getReservationID()); if (queueName != null) { addApplication(appAddedEvent.getApplicationId(), queueName, appAddedEvent.getUser(), appAddedEvent.getIsAppRecovering()); } break; case APP_REMOVED: if (!(event instanceof AppRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent)event; removeApplication(appRemovedEvent.getApplicationID(), appRemovedEvent.getFinalState()); break; case NODE_RESOURCE_UPDATE: if (!(event instanceof NodeResourceUpdateSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } NodeResourceUpdateSchedulerEvent nodeResourceUpdatedEvent = (NodeResourceUpdateSchedulerEvent)event; updateNodeResource(nodeResourceUpdatedEvent.getRMNode(), nodeResourceUpdatedEvent.getResourceOption()); break; case APP_ATTEMPT_ADDED: if (!(event instanceof AppAttemptAddedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAttemptAddedSchedulerEvent appAttemptAddedEvent = (AppAttemptAddedSchedulerEvent) event; addApplicationAttempt(appAttemptAddedEvent.getApplicationAttemptId(), appAttemptAddedEvent.getTransferStateFromPreviousAttempt(), appAttemptAddedEvent.getIsAttemptRecovering()); break; case APP_ATTEMPT_REMOVED: if (!(event instanceof AppAttemptRemovedSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent = (AppAttemptRemovedSchedulerEvent) event; removeApplicationAttempt( appAttemptRemovedEvent.getApplicationAttemptID(), appAttemptRemovedEvent.getFinalAttemptState(), appAttemptRemovedEvent.getKeepContainersAcrossAppAttempts()); break; case CONTAINER_EXPIRED: if (!(event instanceof ContainerExpiredSchedulerEvent)) { throw new RuntimeException("Unexpected event type: " + event); } ContainerExpiredSchedulerEvent containerExpiredEvent = (ContainerExpiredSchedulerEvent)event; ContainerId containerId = containerExpiredEvent.getContainerId(); completedContainer(getRMContainer(containerId), SchedulerUtils.createAbnormalContainerStatus( containerId, SchedulerUtils.EXPIRED_CONTAINER), RMContainerEventType.EXPIRE); break; default: LOG.error("Unknown event arrived at FairScheduler: " + event.toString()); } } private synchronized String resolveReservationQueueName(String queueName, ApplicationId applicationId, ReservationId reservationID) { FSQueue queue = queueMgr.getQueue(queueName); if ((queue == null) || !allocConf.isReservable(queue.getQueueName())) { return queueName; } // Use fully specified name from now on (including root. prefix) queueName = queue.getQueueName(); if (reservationID != null) { String resQName = queueName + "." + reservationID.toString(); queue = queueMgr.getQueue(resQName); if (queue == null) { String message = "Application " + applicationId + " submitted to a reservation which is not yet currently active: " + resQName; this.rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return null; } if (!queue.getParent().getQueueName().equals(queueName)) { String message = "Application: " + applicationId + " submitted to a reservation " + resQName + " which does not belong to the specified queue: " + queueName; this.rmContext.getDispatcher().getEventHandler() .handle(new RMAppRejectedEvent(applicationId, message)); return null; } // use the reservation queue to run the app queueName = resQName; } else { // use the default child queue of the plan for unreserved apps queueName = getDefaultQueueForPlanQueue(queueName); } return queueName; } private String getDefaultQueueForPlanQueue(String queueName) { String planName = queueName.substring(queueName.lastIndexOf(".") + 1); queueName = queueName + "." + planName + ReservationConstants.DEFAULT_QUEUE_SUFFIX; return queueName; } @Override public void recover(RMState state) throws Exception { // NOT IMPLEMENTED } public synchronized void setRMContext(RMContext rmContext) { this.rmContext = rmContext; } private void initScheduler(Configuration conf) throws IOException { synchronized (this) { this.conf = new FairSchedulerConfiguration(conf); validateConf(this.conf); minimumAllocation = this.conf.getMinimumAllocation(); initMaximumResourceCapability(this.conf.getMaximumAllocation()); incrAllocation = this.conf.getIncrementAllocation(); continuousSchedulingEnabled = this.conf.isContinuousSchedulingEnabled(); continuousSchedulingSleepMs = this.conf.getContinuousSchedulingSleepMs(); nodeLocalityThreshold = this.conf.getLocalityThresholdNode(); rackLocalityThreshold = this.conf.getLocalityThresholdRack(); nodeLocalityDelayMs = this.conf.getLocalityDelayNodeMs(); rackLocalityDelayMs = this.conf.getLocalityDelayRackMs(); preemptionEnabled = this.conf.getPreemptionEnabled(); preemptionUtilizationThreshold = this.conf.getPreemptionUtilizationThreshold(); assignMultiple = this.conf.getAssignMultiple(); maxAssign = this.conf.getMaxAssign(); sizeBasedWeight = this.conf.getSizeBasedWeight(); preemptionInterval = this.conf.getPreemptionInterval(); waitTimeBeforeKill = this.conf.getWaitTimeBeforeKill(); usePortForNodeName = this.conf.getUsePortForNodeName(); updateInterval = this.conf.getUpdateInterval(); if (updateInterval < 0) { updateInterval = FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS; LOG.warn(FairSchedulerConfiguration.UPDATE_INTERVAL_MS + " is invalid, so using default value " + +FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS + " ms instead"); } rootMetrics = FSQueueMetrics.forQueue("root", null, true, conf); fsOpDurations = FSOpDurations.getInstance(true); // This stores per-application scheduling information this.applications = new ConcurrentHashMap< ApplicationId, SchedulerApplication<FSAppAttempt>>(); this.eventLog = new FairSchedulerEventLog(); eventLog.init(this.conf); allocConf = new AllocationConfiguration(conf); try { queueMgr.initialize(conf); } catch (Exception e) { throw new IOException("Failed to start FairScheduler", e); } updateThread = new UpdateThread(); updateThread.setName("FairSchedulerUpdateThread"); updateThread.setDaemon(true); if (continuousSchedulingEnabled) { // start continuous scheduling thread schedulingThread = new ContinuousSchedulingThread(); schedulingThread.setName("FairSchedulerContinuousScheduling"); schedulingThread.setDaemon(true); } } allocsLoader.init(conf); allocsLoader.setReloadListener(new AllocationReloadListener()); // If we fail to load allocations file on initialize, we want to fail // immediately. After a successful load, exceptions on future reloads // will just result in leaving things as they are. try { allocsLoader.reloadAllocations(); } catch (Exception e) { throw new IOException("Failed to initialize FairScheduler", e); } } private synchronized void startSchedulerThreads() { Preconditions.checkNotNull(updateThread, "updateThread is null"); Preconditions.checkNotNull(allocsLoader, "allocsLoader is null"); updateThread.start(); if (continuousSchedulingEnabled) { Preconditions.checkNotNull(schedulingThread, "schedulingThread is null"); schedulingThread.start(); } allocsLoader.start(); } @Override public void serviceInit(Configuration conf) throws Exception { initScheduler(conf); super.serviceInit(conf); } @Override public void serviceStart() throws Exception { startSchedulerThreads(); super.serviceStart(); } @Override public void serviceStop() throws Exception { synchronized (this) { if (updateThread != null) { updateThread.interrupt(); updateThread.join(THREAD_JOIN_TIMEOUT_MS); } if (continuousSchedulingEnabled) { if (schedulingThread != null) { schedulingThread.interrupt(); schedulingThread.join(THREAD_JOIN_TIMEOUT_MS); } } if (allocsLoader != null) { allocsLoader.stop(); } } super.serviceStop(); } @Override public void reinitialize(Configuration conf, RMContext rmContext) throws IOException { try { allocsLoader.reloadAllocations(); } catch (Exception e) { LOG.error("Failed to reload allocations file", e); } } @Override public QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive) throws IOException { if (!queueMgr.exists(queueName)) { throw new IOException("queue " + queueName + " does not exist"); } return queueMgr.getQueue(queueName).getQueueInfo(includeChildQueues, recursive); } @Override public List<QueueUserACLInfo> getQueueUserAclInfo() { UserGroupInformation user; try { user = UserGroupInformation.getCurrentUser(); } catch (IOException ioe) { return new ArrayList<QueueUserACLInfo>(); } return queueMgr.getRootQueue().getQueueUserAclInfo(user); } @Override public int getNumClusterNodes() { return nodes.size(); } @Override public synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName) { FSQueue queue = getQueueManager().getQueue(queueName); if (queue == null) { if (LOG.isDebugEnabled()) { LOG.debug("ACL not found for queue access-type " + acl + " for queue " + queueName); } return false; } return queue.hasAccess(acl, callerUGI); } public AllocationConfiguration getAllocationConfiguration() { return allocConf; } private class AllocationReloadListener implements AllocationFileLoaderService.Listener { @Override public void onReload(AllocationConfiguration queueInfo) { // Commit the reload; also create any queue defined in the alloc file // if it does not already exist, so it can be displayed on the web UI. synchronized (FairScheduler.this) { allocConf = queueInfo; allocConf.getDefaultSchedulingPolicy().initialize(clusterResource); queueMgr.updateAllocationConfiguration(allocConf); maxRunningEnforcer.updateRunnabilityOnReload(); } } } @Override public List<ApplicationAttemptId> getAppsInQueue(String queueName) { FSQueue queue = queueMgr.getQueue(queueName); if (queue == null) { return null; } List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>(); queue.collectSchedulerApplications(apps); return apps; } @Override public synchronized String moveApplication(ApplicationId appId, String queueName) throws YarnException { SchedulerApplication<FSAppAttempt> app = applications.get(appId); if (app == null) { throw new YarnException("App to be moved " + appId + " not found."); } FSAppAttempt attempt = (FSAppAttempt) app.getCurrentAppAttempt(); // To serialize with FairScheduler#allocate, synchronize on app attempt synchronized (attempt) { FSLeafQueue oldQueue = (FSLeafQueue) app.getQueue(); String destQueueName = handleMoveToPlanQueue(queueName); FSLeafQueue targetQueue = queueMgr.getLeafQueue(destQueueName, false); if (targetQueue == null) { throw new YarnException("Target queue " + queueName + " not found or is not a leaf queue."); } if (targetQueue == oldQueue) { return oldQueue.getQueueName(); } if (oldQueue.isRunnableApp(attempt)) { verifyMoveDoesNotViolateConstraints(attempt, oldQueue, targetQueue); } executeMove(app, attempt, oldQueue, targetQueue); return targetQueue.getQueueName(); } } private void verifyMoveDoesNotViolateConstraints(FSAppAttempt app, FSLeafQueue oldQueue, FSLeafQueue targetQueue) throws YarnException { String queueName = targetQueue.getQueueName(); ApplicationAttemptId appAttId = app.getApplicationAttemptId(); // When checking maxResources and maxRunningApps, only need to consider // queues before the lowest common ancestor of the two queues because the // total running apps in queues above will not be changed. FSQueue lowestCommonAncestor = findLowestCommonAncestorQueue(oldQueue, targetQueue); Resource consumption = app.getCurrentConsumption(); // Check whether the move would go over maxRunningApps or maxShare FSQueue cur = targetQueue; while (cur != lowestCommonAncestor) { // maxRunningApps if (cur.getNumRunnableApps() == allocConf.getQueueMaxApps(cur.getQueueName())) { throw new YarnException("Moving app attempt " + appAttId + " to queue " + queueName + " would violate queue maxRunningApps constraints on" + " queue " + cur.getQueueName()); } // maxShare if (!Resources.fitsIn(Resources.add(cur.getResourceUsage(), consumption), cur.getMaxShare())) { throw new YarnException("Moving app attempt " + appAttId + " to queue " + queueName + " would violate queue maxShare constraints on" + " queue " + cur.getQueueName()); } cur = cur.getParent(); } } /** * Helper for moveApplication, which has appropriate synchronization, so all * operations will be atomic. */ private void executeMove(SchedulerApplication<FSAppAttempt> app, FSAppAttempt attempt, FSLeafQueue oldQueue, FSLeafQueue newQueue) { boolean wasRunnable = oldQueue.removeApp(attempt); // if app was not runnable before, it may be runnable now boolean nowRunnable = maxRunningEnforcer.canAppBeRunnable(newQueue, attempt.getUser()); if (wasRunnable && !nowRunnable) { throw new IllegalStateException("Should have already verified that app " + attempt.getApplicationId() + " would be runnable in new queue"); } if (wasRunnable) { maxRunningEnforcer.untrackRunnableApp(attempt); } else if (nowRunnable) { // App has changed from non-runnable to runnable maxRunningEnforcer.untrackNonRunnableApp(attempt); } attempt.move(newQueue); // This updates all the metrics app.setQueue(newQueue); newQueue.addApp(attempt, nowRunnable); if (nowRunnable) { maxRunningEnforcer.trackRunnableApp(attempt); } if (wasRunnable) { maxRunningEnforcer.updateRunnabilityOnAppRemoval(attempt, oldQueue); } } @VisibleForTesting FSQueue findLowestCommonAncestorQueue(FSQueue queue1, FSQueue queue2) { // Because queue names include ancestors, separated by periods, we can find // the lowest common ancestors by going from the start of the names until // there's a character that doesn't match. String name1 = queue1.getName(); String name2 = queue2.getName(); // We keep track of the last period we encounter to avoid returning root.apple // when the queues are root.applepie and root.appletart int lastPeriodIndex = -1; for (int i = 0; i < Math.max(name1.length(), name2.length()); i++) { if (name1.length() <= i || name2.length() <= i || name1.charAt(i) != name2.charAt(i)) { return queueMgr.getQueue(name1.substring(0, lastPeriodIndex)); } else if (name1.charAt(i) == '.') { lastPeriodIndex = i; } } return queue1; // names are identical } /** * Process resource update on a node and update Queue. */ @Override public synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption) { super.updateNodeResource(nm, resourceOption); updateRootQueueMetrics(); queueMgr.getRootQueue().setSteadyFairShare(clusterResource); queueMgr.getRootQueue().recomputeSteadyShares(); } /** {@inheritDoc} */ @Override public EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes() { return EnumSet .of(SchedulerResourceTypes.MEMORY, SchedulerResourceTypes.CPU); } @Override public Set<String> getPlanQueues() throws YarnException { Set<String> planQueues = new HashSet<String>(); for (FSQueue fsQueue : queueMgr.getQueues()) { String queueName = fsQueue.getName(); if (allocConf.isReservable(queueName)) { planQueues.add(queueName); } } return planQueues; } @Override public void setEntitlement(String queueName, QueueEntitlement entitlement) throws YarnException { FSLeafQueue reservationQueue = queueMgr.getLeafQueue(queueName, false); if (reservationQueue == null) { throw new YarnException("Target queue " + queueName + " not found or is not a leaf queue."); } reservationQueue.setWeights(entitlement.getCapacity()); // TODO Does MaxCapacity need to be set for fairScheduler ? } /** * Only supports removing empty leaf queues * @param queueName name of queue to remove * @throws YarnException if queue to remove is either not a leaf or if its * not empty */ @Override public void removeQueue(String queueName) throws YarnException { FSLeafQueue reservationQueue = queueMgr.getLeafQueue(queueName, false); if (reservationQueue != null) { if (!queueMgr.removeLeafQueue(queueName)) { throw new YarnException("Could not remove queue " + queueName + " as " + "its either not a leaf queue or its not empty"); } } } private String handleMoveToPlanQueue(String targetQueueName) { FSQueue dest = queueMgr.getQueue(targetQueueName); if (dest != null && allocConf.isReservable(dest.getQueueName())) { // use the default child reservation queue of the plan targetQueueName = getDefaultQueueForPlanQueue(targetQueueName); } return targetQueueName; } /* Start-Wajih Get decision stats*/ @Override public String getDecisionTimeStats() { /* int max_time=0; int min_time=0; // Break down the decision time space into 4 spaces; long part_0_5=0; long part_5_10=0; long part_10_25=0; long part_25_inf=0; String dec_string=" "; boolean flag=true; for(int i =0 ; i< dec_array_size;i++){ if(i>0 && i<=5) part_0_5+=decision_time[i]; if(i>5 && i<=10) part_5_10+=decision_time[i]; if(i>10 && i<=25) part_10_25+=decision_time[i]; if(i>25) part_25_inf+=decision_time[i]; if(flag && decision_time[i] >=1){ min_time=i; flag=false; } if(decision_time[i] >=1){ max_time=i; } dec_string+="Max Time : "; dec_string+=max_time; dec_string+=" ---- "; dec_string+="Min Time : "; dec_string+=min_time; dec_string+="\n"; dec_string+="Percentage of decision timings in between 0-5 Millisecond = "; dec_string+=((part_0_5*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings in between 5-10 Millisecond = "; dec_string+=((part_5_10*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings in between 10-25 Millisecond = "; dec_string+=((part_10_25*1.0)/no_of_decisions)*100; dec_string+="\n"; dec_string+="Percentage of decision timings >25 Millisecond = "; dec_string+=((part_10_25*1.0)/no_of_decisions)*100; } */ return "~~~~~~~~~~~Decision Statistics~~~~~"; /* String decision_str=""; long tmp_sum=0; long tmp_sum2=0; for(int i=0;i<=5;i++) tmp_sum+=decisionArray[i]; decision_str+=" 0-5: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=6;i<=10;i++) tmp_sum+=decisionArray[i]; decision_str+=" 5-10: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=11;i<=25;i++) tmp_sum+=decisionArray[i]; decision_str+=" 10-25: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; tmp_sum=0; for(int i=26;i<=50;i++) tmp_sum+=decisionArray[i]; decision_str+=" 25-50: "+tmp_sum+" "+((int)((tmp_sum*1.0/totalDec)*10000))/100.0+"%"; tmp_sum2+=tmp_sum; return decision_str; */ } /* END -wajih*/ }
Adding Git related Dotfiles
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
Adding Git related Dotfiles
<ide><path>adoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java <ide> /* Start-Wajih Get decision stats*/ <ide> @Override <ide> public String getDecisionTimeStats() { <del> /* <add> <ide> int max_time=0; <ide> int min_time=0; <ide> <ide> long part_25_inf=0; <ide> String dec_string=" "; <ide> boolean flag=true; <del> <del> for(int i =0 ; i< dec_array_size;i++){ <add> System.out.println("No of decisions are = " + no_of_decisions); <add> for(int i=0 ; i<10000; i++){ <ide> if(i>0 && i<=5) <ide> part_0_5+=decision_time[i]; <ide> if(i>5 && i<=10) <ide> dec_string+=((part_10_25*1.0)/no_of_decisions)*100; <ide> <ide> } <del> */ <del> return "~~~~~~~~~~~Decision Statistics~~~~~"; <add> return dec_string; <ide> /* <ide> String decision_str=""; <ide> long tmp_sum=0;
Java
apache-2.0
9b7d4120855343c5327998fb15ee5745a462ec73
0
consulo/consulo,ol-loginov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ibinti/intellij-community,semonte/intellij-community,da1z/intellij-community,fitermay/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ryano144/intellij-community,slisson/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,izonder/intellij-community,FHannes/intellij-community,amith01994/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,dslomov/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,diorcety/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,caot/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,caot/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,clumsy/intellij-community,izonder/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,da1z/intellij-community,fnouama/intellij-community,blademainer/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,ernestp/consulo,holmes/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,slisson/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,holmes/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,allotria/intellij-community,kool79/intellij-community,kool79/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,consulo/consulo,idea4bsd/idea4bsd,dslomov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,allotria/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,slisson/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,izonder/intellij-community,holmes/intellij-community,retomerz/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,apixandru/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,fnouama/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,signed/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,akosyakov/intellij-community,supersven/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,caot/intellij-community,Distrotech/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,amith01994/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,dslomov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,fnouama/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,clumsy/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,semonte/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,apixandru/intellij-community,retomerz/intellij-community,petteyg/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,blademainer/intellij-community,signed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,samthor/intellij-community,supersven/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,youdonghai/intellij-community,kool79/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fitermay/intellij-community,izonder/intellij-community,Distrotech/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,da1z/intellij-community,adedayo/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,caot/intellij-community,kool79/intellij-community,fnouama/intellij-community,ernestp/consulo,youdonghai/intellij-community,nicolargo/intellij-community,holmes/intellij-community,diorcety/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,dslomov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,signed/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,allotria/intellij-community,dslomov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,supersven/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ryano144/intellij-community,ryano144/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,signed/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,signed/intellij-community,clumsy/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,consulo/consulo,youdonghai/intellij-community,slisson/intellij-community,orekyuu/intellij-community,semonte/intellij-community,gnuhub/intellij-community,kool79/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,samthor/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,izonder/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,allotria/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,apixandru/intellij-community,da1z/intellij-community,fnouama/intellij-community,caot/intellij-community,supersven/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,ryano144/intellij-community,ryano144/intellij-community,signed/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,dslomov/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,consulo/consulo,kdwink/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,joewalnes/idea-community,adedayo/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,adedayo/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,hurricup/intellij-community,xfournet/intellij-community,apixandru/intellij-community,supersven/intellij-community,FHannes/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,signed/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,petteyg/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,izonder/intellij-community,diorcety/intellij-community,caot/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ryano144/intellij-community,hurricup/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,vladmm/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,adedayo/intellij-community,apixandru/intellij-community,dslomov/intellij-community,amith01994/intellij-community,caot/intellij-community,ryano144/intellij-community,ibinti/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,hurricup/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,FHannes/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,allotria/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,jagguli/intellij-community,ernestp/consulo,pwoodworth/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,allotria/intellij-community,joewalnes/idea-community,joewalnes/idea-community,salguarnieri/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,supersven/intellij-community,da1z/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,consulo/consulo,ahb0327/intellij-community,robovm/robovm-studio,ibinti/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,supersven/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,fitermay/intellij-community,da1z/intellij-community,kool79/intellij-community,samthor/intellij-community,allotria/intellij-community,vladmm/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,semonte/intellij-community,kool79/intellij-community,hurricup/intellij-community,caot/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,vladmm/intellij-community,samthor/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,allotria/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,jagguli/intellij-community,ernestp/consulo,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,semonte/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,petteyg/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,adedayo/intellij-community,kool79/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.runner; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; import java.io.IOException; /** * @author peter */ public abstract class GroovyScriptRunner { public abstract boolean isValidModule(@NotNull Module module); public abstract boolean ensureRunnerConfigured(@Nullable Module module, RunProfile profile, final Project project) throws ExecutionException; public abstract void configureCommandLine(JavaParameters params, @Nullable Module module, boolean tests, VirtualFile script, GroovyScriptRunConfiguration configuration) throws CantRunException; protected static String getConfPath(final String groovyHomePath) { String confpath = FileUtil.toSystemDependentName(groovyHomePath + "/conf/groovy-starter.conf"); if (new File(confpath).exists()) { return confpath; } try { final String jarPath = PathUtil.getJarPathForClass(GroovyScriptRunner.class); if (new File(jarPath).isFile()) { //jar; distribution mode return new File(jarPath, "../groovy-starter.conf").getCanonicalPath(); } //else, it's directory in out, development mode return new File(jarPath, "conf/groovy-starter.conf").getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } protected static void setGroovyHome(JavaParameters params, String groovyHome) { params.getVMParametersList().add("-Dgroovy.home=" + groovyHome); if (groovyHome.contains("grails")) { //a bit of a hack params.getVMParametersList().add("-Dgrails.home=" + groovyHome); } if (groovyHome.contains("griffon")) { //a bit of a hack params.getVMParametersList().add("-Dgriffon.home=" + groovyHome); } } protected static void setToolsJar(JavaParameters params) { Sdk jdk = params.getJdk(); if (jdk != null && jdk.getSdkType() instanceof JavaSdkType) { String toolsPath = ((JavaSdkType)jdk.getSdkType()).getToolsPath(jdk); if (toolsPath != null) { params.getVMParametersList().add("-Dtools.jar=" + toolsPath); } } } @Nullable protected static VirtualFile findGroovyJar(@NotNull Module module) { final VirtualFile[] files = ModuleRootManager.getInstance(module).getFiles(OrderRootType.CLASSES); for (VirtualFile root : files) { if (root.getName().matches(GroovyConfigUtils.GROOVY_JAR_PATTERN) || root.getName().matches(GroovyConfigUtils.GROOVY_ALL_JAR_PATTERN)) { return root; } } for (VirtualFile file : files) { if (file.getName().contains("groovy") && "jar".equals(file.getExtension())) { return file; } } return null; } protected static void addClasspathFromRootModel(@Nullable Module module, boolean isTests, JavaParameters params) throws CantRunException { if (module == null) { return; } final JavaParameters tmp = new JavaParameters(); tmp.configureByModule(module, isTests ? JavaParameters.CLASSES_AND_TESTS : JavaParameters.CLASSES_ONLY); if (tmp.getClassPath().getVirtualFiles().isEmpty()) { return; } params.getProgramParametersList().add("--classpath"); params.getProgramParametersList().add(tmp.getClassPath().getPathsString()); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyScriptRunner.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.runner; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; import java.io.IOException; /** * @author peter */ public abstract class GroovyScriptRunner { public abstract boolean isValidModule(@NotNull Module module); public abstract boolean ensureRunnerConfigured(@Nullable Module module, RunProfile profile, final Project project) throws ExecutionException; public abstract void configureCommandLine(JavaParameters params, @Nullable Module module, boolean tests, VirtualFile script, GroovyScriptRunConfiguration configuration) throws CantRunException; protected static String getConfPath(final String groovyHomePath) { String confpath = FileUtil.toSystemDependentName(groovyHomePath + "/conf/groovy-starter.conf"); if (new File(confpath).exists()) { return confpath; } try { final String jarPath = PathUtil.getJarPathForClass(GroovyScriptRunner.class); if (new File(jarPath).isFile()) { //jar; distribution mode return new File(jarPath, "../groovy-starter.conf").getCanonicalPath(); } //else, it's directory in out, development mode return new File(jarPath, "conf/groovy-starter.conf").getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } protected static void setGroovyHome(JavaParameters params, String groovyHome) { params.getVMParametersList().add("-Dgroovy.home=" + groovyHome); if (groovyHome.contains("grails")) { //a bit of a hack params.getVMParametersList().add("-Dgrails.home=" + groovyHome); } if (groovyHome.contains("griffon")) { //a bit of a hack params.getVMParametersList().add("-Dgriffon.home=" + groovyHome); } } protected static void setToolsJar(JavaParameters params) { Sdk jdk = params.getJdk(); if (jdk != null && jdk.getSdkType() instanceof JavaSdkType) { String toolsPath = ((JavaSdkType)jdk.getSdkType()).getToolsPath(jdk); if (toolsPath != null) { params.getVMParametersList().add("-Dtools.jar=" + toolsPath); } } } @Nullable protected static VirtualFile findGroovyJar(@NotNull Module module) { final VirtualFile[] files = ModuleRootManager.getInstance(module).getFiles(OrderRootType.CLASSES); for (VirtualFile root : files) { if (GroovyConfigUtils.GROOVY_JAR_PATTERN.matches(root.getName()) || GroovyConfigUtils.GROOVY_ALL_JAR_PATTERN.matches(root.getName())) { return root; } } for (VirtualFile file : files) { if (file.getName().contains("groovy") && "jar".equals(file.getExtension())) { return file; } } return null; } protected static void addClasspathFromRootModel(@Nullable Module module, boolean isTests, JavaParameters params) throws CantRunException { if (module == null) { return; } final JavaParameters tmp = new JavaParameters(); tmp.configureByModule(module, isTests ? JavaParameters.CLASSES_AND_TESTS : JavaParameters.CLASSES_ONLY); if (tmp.getClassPath().getVirtualFiles().isEmpty()) { return; } params.getProgramParametersList().add("--classpath"); params.getProgramParametersList().add(tmp.getClassPath().getPathsString()); } }
string.matches(pattern), not vice versa
plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyScriptRunner.java
string.matches(pattern), not vice versa
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyScriptRunner.java <ide> protected static VirtualFile findGroovyJar(@NotNull Module module) { <ide> final VirtualFile[] files = ModuleRootManager.getInstance(module).getFiles(OrderRootType.CLASSES); <ide> for (VirtualFile root : files) { <del> if (GroovyConfigUtils.GROOVY_JAR_PATTERN.matches(root.getName()) || GroovyConfigUtils.GROOVY_ALL_JAR_PATTERN.matches(root.getName())) { <add> if (root.getName().matches(GroovyConfigUtils.GROOVY_JAR_PATTERN) || root.getName().matches(GroovyConfigUtils.GROOVY_ALL_JAR_PATTERN)) { <ide> return root; <ide> } <ide> }
Java
apache-2.0
15e75b11fe80734207180d1fa0bc9371cf58fb41
0
wurstscript/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,peq/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,wurstscript/WurstScript
package de.peeeq.wurstio.languageserver.requests; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.io.Files; import de.peeeq.wurstio.CompiletimeFunctionRunner; import de.peeeq.wurstio.UtilsIO; import de.peeeq.wurstio.WurstCompilerJassImpl; import de.peeeq.wurstio.languageserver.ModelManager; import de.peeeq.wurstio.languageserver.WFile; import de.peeeq.wurstio.map.importer.ImportFile; import de.peeeq.wurstio.mpq.MpqEditor; import de.peeeq.wurstio.mpq.MpqEditorFactory; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.CompilationUnit; import de.peeeq.wurstscript.ast.WImport; import de.peeeq.wurstscript.ast.WPackage; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import de.peeeq.wurstscript.jassAst.JassProg; import de.peeeq.wurstscript.jassprinter.JassPrinter; import de.peeeq.wurstscript.parser.WPos; import de.peeeq.wurstscript.utils.LineOffsets; import de.peeeq.wurstscript.utils.Utils; import org.eclipse.lsp4j.MessageParams; import org.eclipse.lsp4j.MessageType; import org.eclipse.lsp4j.services.LanguageClient; import java.io.File; import java.io.PrintStream; import java.nio.channels.NonWritableChannelException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static de.peeeq.wurstio.CompiletimeFunctionRunner.FunctionFlagToRun.CompiletimeFunctions; public abstract class MapRequest extends UserRequest<Object> { protected final File map; protected final List<String> compileArgs; protected final WFile workspaceRoot; public MapRequest(File map, List<String> compileArgs, WFile workspaceRoot) { this.map = map; this.compileArgs = compileArgs; this.workspaceRoot = workspaceRoot; } @Override public void handleException(LanguageClient languageClient, Throwable err, CompletableFuture<Object> resFut) { if (err instanceof RequestFailedException) { RequestFailedException rfe = (RequestFailedException) err; languageClient.showMessage(new MessageParams(rfe.getMessageType(), rfe.getMessage())); resFut.complete(new Object()); } else { super.handleException(languageClient, err, resFut); } } protected void processMapScript(RunArgs runArgs, WurstGui gui, ModelManager modelManager, File mapCopy) throws Exception { File existingScript = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j"); // If runargs are no extract, either use existing or throw error // Otherwise try loading from map, if map was saved with wurst, try existing script, otherwise error if (runArgs.isNoExtractMapScript()) { WLogger.info("flag -isNoExtractMapScript set"); if (existingScript.exists()) { modelManager.syncCompilationUnit(WFile.create(existingScript)); return; } else { throw new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0), "RunArg noExtractMapScript is set but no mapscript is provided inside the wurst folder"); } } WLogger.info("extracting mapscript"); byte[] extractedScript; try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) { extractedScript = mpqEditor.extractFile("war3map.j"); } if (new String(extractedScript, StandardCharsets.UTF_8).startsWith(JassPrinter.WURST_COMMENT_RAW)) { WLogger.info("map has already been compiled with wurst"); // file generated by wurst, do not use if (existingScript.exists()) { WLogger.info( "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Using war3map.j from Wurst directory instead."); } else { CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0), "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Please add war3map.j to the wurst directory."); gui.showInfoMessage(err.getMessage()); WLogger.severe(err); } } else { WLogger.info("new map, use extracted"); // write mapfile from map to workspace Files.write(extractedScript, existingScript); } // push war3map.j to modelmanager modelManager.syncCompilationUnit(WFile.create(existingScript)); } protected File compileMap(WurstGui gui, File mapCopy, File origMap, RunArgs runArgs, WurstModel model) { try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) { //WurstGui gui = new WurstGuiLogger(); if (!mpqEditor.canWrite()) { WLogger.severe("The supplied map is invalid/corrupted/protected and Wurst cannot write to it.\n" + "Please supply a valid .w3x input map that can be opened in the world editor."); throw new NonWritableChannelException(); } WurstCompilerJassImpl compiler = new WurstCompilerJassImpl(gui, mpqEditor, runArgs); compiler.setMapFile(mapCopy); purgeUnimportedFiles(model); gui.sendProgress("Check program"); compiler.checkProg(model); if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Warning, "Could not compile project: " + gui.getErrorList().get(0)); } print("translating program ... "); compiler.translateProgToIm(model); if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Error, "Could not compile project (error in translation): " + gui.getErrorList().get(0)); } if (runArgs.runCompiletimeFunctions()) { print("running compiletime functions ... "); // compile & inject object-editor data // TODO run optimizations later? gui.sendProgress("Running compiletime functions"); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), compiler.getMapfileMpqEditor(), gui, CompiletimeFunctions); ctr.setInjectObjects(runArgs.isInjectObjects()); ctr.setOutputStream(new PrintStream(System.err)); ctr.run(); } if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Error, "Could not compile project (error in running compiletime functions/expressions): " + gui .getErrorList().get(0)); } if (runArgs.isInjectObjects()) { Preconditions.checkNotNull(mpqEditor); // add the imports ImportFile.importFilesFromImportDirectory(origMap, mpqEditor); } print("translating program to jass ... "); compiler.transformProgToJass(); JassProg jassProg = compiler.getProg(); if (jassProg == null) { print("Could not compile project\n"); throw new RuntimeException("Could not compile project (error in JASS translation)"); } gui.sendProgress("Printing program"); JassPrinter printer = new JassPrinter(!runArgs.isOptimize(), jassProg); String compiledMapScript = printer.printProg(); File buildDir = getBuildDir(); File outFile = new File(buildDir, "compiled.j.txt"); Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile); return outFile; } catch (Exception e) { throw new RuntimeException(e); } } /** * removes everything compilation unit which is neither * - inside a wurst folder * - a jass file * - imported by a file in a wurst folder */ private void purgeUnimportedFiles(WurstModel model) { Set<CompilationUnit> imported = model.stream() .filter(cu -> isInWurstFolder(cu.getFile()) || cu.getFile().endsWith(".j")).distinct().collect(Collectors.toSet()); addImports(imported, imported); model.removeIf(cu -> !imported.contains(cu)); } private boolean isInWurstFolder(String file) { Path p = Paths.get(file); Path w = workspaceRoot.getPath(); return p.startsWith(w) && java.nio.file.Files.exists(p) && Utils.isWurstFile(file); } protected File getBuildDir() { File buildDir = new File(workspaceRoot.getFile(), "_build"); if (!buildDir.exists()) { UtilsIO.mkdirs(buildDir); } return buildDir; } private void addImports(Set<CompilationUnit> result, Set<CompilationUnit> toAdd) { Set<CompilationUnit> imported = toAdd.stream() .flatMap((CompilationUnit cu) -> cu.getPackages().stream()) .flatMap((WPackage p) -> p.getImports().stream()) .map(WImport::attrImportedPackage) .filter(Objects::nonNull) .map(WPackage::attrCompilationUnit) .collect(Collectors.toSet()); boolean changed = result.addAll(imported); if (changed) { // recursive call terminates, as there are only finitely many compilation units addImports(result, imported); } } protected void print(String s) { WLogger.info(s); } protected void println(String s) { WLogger.info(s); } }
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/MapRequest.java
package de.peeeq.wurstio.languageserver.requests; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.io.Files; import de.peeeq.wurstio.CompiletimeFunctionRunner; import de.peeeq.wurstio.UtilsIO; import de.peeeq.wurstio.WurstCompilerJassImpl; import de.peeeq.wurstio.languageserver.ModelManager; import de.peeeq.wurstio.languageserver.WFile; import de.peeeq.wurstio.map.importer.ImportFile; import de.peeeq.wurstio.mpq.MpqEditor; import de.peeeq.wurstio.mpq.MpqEditorFactory; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.CompilationUnit; import de.peeeq.wurstscript.ast.WImport; import de.peeeq.wurstscript.ast.WPackage; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import de.peeeq.wurstscript.jassAst.JassProg; import de.peeeq.wurstscript.jassprinter.JassPrinter; import de.peeeq.wurstscript.parser.WPos; import de.peeeq.wurstscript.utils.LineOffsets; import de.peeeq.wurstscript.utils.Utils; import org.eclipse.lsp4j.MessageParams; import org.eclipse.lsp4j.MessageType; import org.eclipse.lsp4j.services.LanguageClient; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.channels.NonWritableChannelException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static de.peeeq.wurstio.CompiletimeFunctionRunner.FunctionFlagToRun.CompiletimeFunctions; public abstract class MapRequest extends UserRequest<Object> { protected final File map; protected final List<String> compileArgs; protected final WFile workspaceRoot; public MapRequest(File map, List<String> compileArgs, WFile workspaceRoot) { this.map = map; this.compileArgs = compileArgs; this.workspaceRoot = workspaceRoot; } @Override public void handleException(LanguageClient languageClient, Throwable err, CompletableFuture<Object> resFut) { if (err instanceof RequestFailedException) { RequestFailedException rfe = (RequestFailedException) err; languageClient.showMessage(new MessageParams(rfe.getMessageType(), rfe.getMessage())); resFut.complete(new Object()); } else { super.handleException(languageClient, err, resFut); } } protected void processMapScript(RunArgs runArgs, WurstGui gui, ModelManager modelManager, File mapCopy) throws Exception { File existingScript = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j"); // If runargs are no extract, either use existing or throw error // Otherwise try loading from map, if map was saved with wurst, try existing script, otherwise error if (runArgs.isNoExtractMapScript()) { WLogger.info("flag -isNoExtractMapScript set"); if (existingScript.exists()) { modelManager.syncCompilationUnit(WFile.create(existingScript)); return; } else { throw new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0), "RunArg noExtractMapScript is set but no mapscript is provided inside the wurst folder"); } } WLogger.info("extracting mapscript"); byte[] extractedScript; try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) { extractedScript = mpqEditor.extractFile("war3map.j"); } if (new String(extractedScript, StandardCharsets.UTF_8).startsWith(JassPrinter.WURST_COMMENT_RAW)) { WLogger.info("map has already been compiled with wurst"); // file generated by wurst, do not use if (existingScript.exists()) { WLogger.info( "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Using war3map.j from Wurst directory instead."); } else { CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0), "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Please add war3map.j to the wurst directory."); gui.showInfoMessage(err.getMessage()); WLogger.severe(err); } } else { WLogger.info("new map, use extracted"); // write mapfile from map to workspace Files.write(extractedScript, existingScript); } // push war3map.j to modelmanager modelManager.syncCompilationUnit(WFile.create(existingScript)); } protected File compileMap(WurstGui gui, File mapCopy, File origMap, RunArgs runArgs, WurstModel model) { try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) { //WurstGui gui = new WurstGuiLogger(); if (!mpqEditor.canWrite()) { WLogger.severe("The supplied map is invalid/corrupted/protected and Wurst cannot write to it.\n" + "Please supply a valid .w3x input map that can be opened in the world editor."); throw new NonWritableChannelException(); } WurstCompilerJassImpl compiler = new WurstCompilerJassImpl(gui, mpqEditor, runArgs); compiler.setMapFile(mapCopy); purgeUnimportedFiles(model); gui.sendProgress("Check program"); compiler.checkProg(model); if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Warning, "Could not compile project: " + gui.getErrorList().get(0)); } print("translating program ... "); compiler.translateProgToIm(model); if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Error, "Could not compile project (error in translation): " + gui.getErrorList().get(0)); } if (runArgs.runCompiletimeFunctions()) { print("running compiletime functions ... "); // compile & inject object-editor data // TODO run optimizations later? gui.sendProgress("Running compiletime functions"); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), compiler.getMapfileMpqEditor(), gui, CompiletimeFunctions); ctr.setInjectObjects(runArgs.isInjectObjects()); ctr.setOutputStream(new PrintStream(System.err)); ctr.run(); } if (gui.getErrorCount() > 0) { throw new RequestFailedException(MessageType.Error, "Could not compile project (error in running compiletime functions/expressions): " + gui.getErrorList().get(0)); } if (runArgs.isInjectObjects()) { Preconditions.checkNotNull(mpqEditor); // add the imports ImportFile.importFilesFromImportDirectory(origMap, mpqEditor); } print("translating program to jass ... "); compiler.transformProgToJass(); JassProg jassProg = compiler.getProg(); if (jassProg == null) { print("Could not compile project\n"); throw new RuntimeException("Could not compile project (error in JASS translation)"); } gui.sendProgress("Printing program"); JassPrinter printer = new JassPrinter(!runArgs.isOptimize(), jassProg); String compiledMapScript = printer.printProg(); File buildDir = getBuildDir(); File outFile = new File(buildDir, "compiled.j.txt"); Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile); return outFile; } catch (Exception e) { throw new RuntimeException(e); } } /** * removes everything compilation unit which is neither * - inside a wurst folder * - a jass file * - imported by a file in a wurst folder */ private void purgeUnimportedFiles(WurstModel model) { Set<CompilationUnit> imported = model.stream() .filter(cu -> isInWurstFolder(cu.getFile()) || cu.getFile().endsWith(".j")).distinct().collect(Collectors.toSet()); addImports(imported, imported); model.removeIf(cu -> !imported.contains(cu)); } private boolean isInWurstFolder(String file) { Path p = Paths.get(file); Path w = workspaceRoot.getPath(); return p.startsWith(w) && java.nio.file.Files.exists(p) && Utils.isWurstFile(file); } protected File getBuildDir() { File buildDir = new File(workspaceRoot.getFile(), "_build"); UtilsIO.mkdirs(buildDir); return buildDir; } private void addImports(Set<CompilationUnit> result, Set<CompilationUnit> toAdd) { Set<CompilationUnit> imported = toAdd.stream() .flatMap((CompilationUnit cu) -> cu.getPackages().stream()) .flatMap((WPackage p) -> p.getImports().stream()) .map(WImport::attrImportedPackage) .filter(Objects::nonNull) .map(WPackage::attrCompilationUnit) .collect(Collectors.toSet()); boolean changed = result.addAll(imported); if (changed) { // recursive call terminates, as there are only finitely many compilation units addImports(result, imported); } } protected void print(String s) { WLogger.info(s); } protected void println(String s) { WLogger.info(s); } }
fix trying to create build dir when it already exists
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/MapRequest.java
fix trying to create build dir when it already exists
<ide><path>e.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/MapRequest.java <ide> import org.eclipse.lsp4j.services.LanguageClient; <ide> <ide> import java.io.File; <del>import java.io.IOException; <ide> import java.io.PrintStream; <ide> import java.nio.channels.NonWritableChannelException; <ide> import java.nio.charset.StandardCharsets; <ide> } <ide> <ide> if (gui.getErrorCount() > 0) { <del> throw new RequestFailedException(MessageType.Error, "Could not compile project (error in running compiletime functions/expressions): " + gui.getErrorList().get(0)); <del> } <del> <add> throw new RequestFailedException(MessageType.Error, "Could not compile project (error in running compiletime functions/expressions): " + gui <add> .getErrorList().get(0)); <add> } <ide> <ide> <ide> if (runArgs.isInjectObjects()) { <ide> <ide> protected File getBuildDir() { <ide> File buildDir = new File(workspaceRoot.getFile(), "_build"); <del> UtilsIO.mkdirs(buildDir); <add> if (!buildDir.exists()) { <add> UtilsIO.mkdirs(buildDir); <add> } <ide> return buildDir; <ide> } <ide>
Java
apache-2.0
fa7cb010469731bd9b17610eb32962faf12360b1
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package io.jenetics.ext.moea; import static io.jenetics.internal.math.base.clamp; import java.util.Comparator; import io.jenetics.ext.moea.Vecs.DoubleVec; import io.jenetics.ext.moea.Vecs.IntVec; import io.jenetics.ext.moea.Vecs.LongVec; import io.jenetics.ext.moea.Vecs.ObjectVec; /** * The {@code Vec} interface represents the fitness result of a multi-objective * fitness function. It also defines a set of static factory methods which * allows you to create {@code Vec} instance from a given {@code int[]}, * {@code long[]} or {@code double[]} array. * * <pre>{@code * final Vec<double[]> point2D = Vec.of(0.1, 5.4); * final Vec<int[]> point3D = Vec.of(1, 2, 3); * }</pre> * * The underlying array is <em>just</em> wrapped and <em>not</em> copied. This * means you can change the values of the {@code Vec} once it is created, * <em>Not copying the underlying array is done for performance reason. Changing * the {@code Vec} data is, of course, never a good idea.</em> * * @implNote * Although the {@code Vec} interface extends the {@link Comparable} interface, * it violates its <em>general</em> contract. It <em>only</em> * implements the pareto <em>dominance</em> relation, which defines a partial * order. So, trying to sort a list of {@code Vec} objects, might lead * to an exception (thrown by the sorting method) at runtime. * * @param <T> the underlying array type, like {@code int[]} or {@code double[]} * * @see <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * Pareto efficiency</a> * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version 4.1 * @since 4.1 */ public interface Vec<T> extends Comparable<Vec<T>> { /** * Return the underlying data structure. * * @return the underlying data structure */ public T data(); /** * Return the number of vector elements. * * @return the number of vector elements */ public int length(); /** * Return the comparator for comparing the elements of this MO vector. * * @return the comparator for comparing the elements of this MO vector */ public ElementComparator<T> comparator(); /** * Return a function which calculates the element distance of a vector at a * given element index. * * @return a function which calculates the element distance of a vector at a * given element index */ public ElementDistance<T> distance(); /** * Return the comparator which defines the (Pareto) dominance measure. * * @return the comparator which defines the (Pareto) dominance measure */ public Comparator<T> dominance(); /* ************************************************************************* * Default methods derived from the methods above. * ************************************************************************/ /** * Compares the {@code this} vector with the {@code other} at the given * component {@code index}. * * @param other the other vector * @param index the component index * @return a negative integer, zero, or a positive integer as * {@code this[index]} is less than, equal to, or greater than * {@code other[index]} * @throws NullPointerException if the {@code other} object is {@code null} * @throws IllegalArgumentException if the {@code index} is out of the valid * range {@code [0, length())} */ public default int compare(final Vec<T> other, final int index) { return comparator().compare(data(), other.data(), index); } /** * Calculates the distance between two vector elements at the given * {@code index}. * * @param other the second vector * @param index the vector element index * @return the distance between two vector elements * @throws NullPointerException if the {@code other} vector is {@code null} * @throws IllegalArgumentException if the {@code index} is out of the valid * range {@code [0, length())} */ public default double distance(final Vec<T> other, final int index) { return distance().distance(data(), other.data(), index); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of vector {@code value()} and {@code other}. * * @param other the other vector * @return {@code 1} if <b>value()</b> ≻ <b>other</b>, {@code -1} if * <b>other</b> ≻ <b>value()</b> and {@code 0} otherwise * @throws NullPointerException if the {@code other} vector is {@code null} */ public default int dominance(final Vec<T> other) { return dominance().compare(data(), other.data()); } /** * The default implementation uses the {@link #dominance(Vec)} function * for defining a <b>partial</b> order of two vectors. * * @param other the other vector * @return {@code 1} if <b>value()</b> ≻ <b>other</b>, {@code -1} if * <b>other</b> ≻ <b>value()</b> and {@code 0} otherwise * @throws NullPointerException if the {@code other} vector is {@code null} */ @Override public default int compareTo(final Vec<T> other) { return dominance(other); } /* ************************************************************************* * Common 'dominance' methods. * ************************************************************************/ /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(Comparable[], Comparable[]) * * @param u the first vector * @param v the second vector * @param <C> the element type of vector <b>u</b> and <b>v</b> * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static <C extends Comparable<? super C>> int dominance(final C[] u, final C[] v) { return dominance(u, v, Comparator.naturalOrder()); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(Object[], Object[], Comparator) * * @param u the first vector * @param v the second vector * @param comparator the element comparator which is used for calculating * the dominance * @param <T> the element type of vector <b>u</b> and <b>v</b> * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static <T> int dominance(final T[] u, final T[] v, final Comparator<? super T> comparator) { return Pareto.dominance(u, v, comparator); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(int[], int[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final int[] u, final int[] v) { return Pareto.dominance(u, v); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(long[], long[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final long[] u, final long[] v) { return Pareto.dominance(u, v); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(double[], double[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final double[] u, final double[] v) { return Pareto.dominance(u, v); } /* ************************************************************************* * Static factory functions for wrapping ordinary arrays. * ************************************************************************/ /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param <C> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <C extends Comparable<? super C>> Vec<C[]> of(final C[] array) { return of( array, (u, v, i) -> clamp(u[i].compareTo(v[i]), -1, 1) ); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param distance the array element distance measure * @param <C> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <C extends Comparable<? super C>> Vec<C[]> of( final C[] array, final ElementDistance<C[]> distance ) { return of(array, Comparator.naturalOrder(), distance); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param comparator the (natural order) comparator of the array elements * @param distance the distance function between two vector elements * @param <T> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <T> Vec<T[]> of( final T[] array, final Comparator<? super T> comparator, final ElementDistance<T[]> distance ) { return new ObjectVec<>(array, comparator, distance); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<int[]> of(final int... array) { return new IntVec(array); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<long[]> of(final long... array) { return new LongVec(array); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<double[]> of(final double... array) { return new DoubleVec(array); } }
jenetics.ext/src/main/java/io/jenetics/ext/moea/Vec.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package io.jenetics.ext.moea; import static io.jenetics.internal.math.base.clamp; import java.util.Comparator; import io.jenetics.ext.moea.Vecs.DoubleVec; import io.jenetics.ext.moea.Vecs.IntVec; import io.jenetics.ext.moea.Vecs.LongVec; import io.jenetics.ext.moea.Vecs.ObjectVec; /** * The {@code Vec} interface represents the fitness result of a multi-objective * fitness function. It also defines a set of static factory methods which * allows you to create {@code Vec} instance from a given {@code int[]}, * {@code long[]} or {@code double[]} array. * * <pre>{@code * final Vec<double[]> point2D = Vec.of(0.1, 5.4); * final Vec<int[]> point3D = Vec.of(1, 2, 3); * }</pre> * * @implNote * Although the {@code Vec} interface extends the {@link Comparable} interface, * it violates its <em>general</em> contract. It <em>only</em> * implements the pareto <em>dominance</em> relation, which defines a partial * order. So, trying to sort a list of {@code Vec} objects, might lead * to an exception (thrown by the sorting method) at runtime. * * @param <T> the underlying data type, like {@code int[]} or {@code double[]} * * @see <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * Pareto efficiency</a> * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version 4.1 * @since 4.1 */ public interface Vec<T> extends Comparable<Vec<T>> { /** * Return the underlying data structure. * * @return the underlying data structure */ public T data(); /** * Return the number of vector elements. * * @return the number of vector elements */ public int length(); /** * Return the comparator for comparing the elements of this MO vector. * * @return the comparator for comparing the elements of this MO vector */ public ElementComparator<T> comparator(); /** * Return a function which calculates the element distance of a vector at a * given element index. * * @return a function which calculates the element distance of a vector at a * given element index */ public ElementDistance<T> distance(); /** * Return the comparator which defines the (Pareto) dominance measure. * * @return the comparator which defines the (Pareto) dominance measure */ public Comparator<T> dominance(); /* ************************************************************************* * Default methods derived from the methods above. * ************************************************************************/ /** * Compares the {@code this} vector with the {@code other} at the given * component {@code index}. * * @param other the other vector * @param index the component index * @return a negative integer, zero, or a positive integer as * {@code this[index]} is less than, equal to, or greater than * {@code other[index]} * @throws NullPointerException if the {@code other} object is {@code null} * @throws IllegalArgumentException if the {@code index} is out of the valid * range {@code [0, length())} */ public default int compare(final Vec<T> other, final int index) { return comparator().compare(data(), other.data(), index); } /** * Calculates the distance between two vector elements at the given * {@code index}. * * @param other the second vector * @param index the vector element index * @return the distance between two vector elements * @throws NullPointerException if the {@code other} vector is {@code null} * @throws IllegalArgumentException if the {@code index} is out of the valid * range {@code [0, length())} */ public default double distance(final Vec<T> other, final int index) { return distance().distance(data(), other.data(), index); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of vector {@code value()} and {@code other}. * * @param other the other vector * @return {@code 1} if <b>value()</b> ≻ <b>other</b>, {@code -1} if * <b>other</b> ≻ <b>value()</b> and {@code 0} otherwise * @throws NullPointerException if the {@code other} vector is {@code null} */ public default int dominance(final Vec<T> other) { return dominance().compare(data(), other.data()); } /** * The default implementation uses the {@link #dominance(Vec)} function * for defining a <b>partial</b> order of two vectors. * * @param other the other vector * @return {@code 1} if <b>value()</b> ≻ <b>other</b>, {@code -1} if * <b>other</b> ≻ <b>value()</b> and {@code 0} otherwise * @throws NullPointerException if the {@code other} vector is {@code null} */ @Override public default int compareTo(final Vec<T> other) { return dominance(other); } /* ************************************************************************* * Common 'dominance' methods. * ************************************************************************/ /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(Comparable[], Comparable[]) * * @param u the first vector * @param v the second vector * @param <C> the element type of vector <b>u</b> and <b>v</b> * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static <C extends Comparable<? super C>> int dominance(final C[] u, final C[] v) { return dominance(u, v, Comparator.naturalOrder()); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(Object[], Object[], Comparator) * * @param u the first vector * @param v the second vector * @param comparator the element comparator which is used for calculating * the dominance * @param <T> the element type of vector <b>u</b> and <b>v</b> * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static <T> int dominance(final T[] u, final T[] v, final Comparator<? super T> comparator) { return Pareto.dominance(u, v, comparator); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(int[], int[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final int[] u, final int[] v) { return Pareto.dominance(u, v); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(long[], long[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final long[] u, final long[] v) { return Pareto.dominance(u, v); } /** * Calculates the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> * <b>Pareto Dominance</b></a> of the two vectors <b>u</b> and <b>v</b>. * * @see Pareto#dominance(double[], double[]) * * @param u the first vector * @param v the second vector * @return {@code 1} if <b>u</b> ≻ <b>v</b>, {@code -1} if <b>v</b> ≻ * <b>u</b> and {@code 0} otherwise * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if {@code u.length != v.length} */ public static int dominance(final double[] u, final double[] v) { return Pareto.dominance(u, v); } /* ************************************************************************* * Static factory functions for wrapping ordinary arrays. * ************************************************************************/ /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param <C> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <C extends Comparable<? super C>> Vec<C[]> of(final C[] array) { return of( array, (u, v, i) -> clamp(u[i].compareTo(v[i]), -1, 1) ); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param distance the array element distance measure * @param <C> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <C extends Comparable<? super C>> Vec<C[]> of( final C[] array, final ElementDistance<C[]> distance ) { return of(array, Comparator.naturalOrder(), distance); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @param comparator the (natural order) comparator of the array elements * @param distance the distance function between two vector elements * @param <T> the array element type * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static <T> Vec<T[]> of( final T[] array, final Comparator<? super T> comparator, final ElementDistance<T[]> distance ) { return new ObjectVec<>(array, comparator, distance); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<int[]> of(final int... array) { return new IntVec(array); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<long[]> of(final long... array) { return new LongVec(array); } /** * Wraps the given array into a {@code Vec} object. * * @param array the wrapped array * @return the given array wrapped into a {@code Vec} object. * @throws NullPointerException if the given {@code array} is {@code null} * @throws IllegalArgumentException if the {@code array} length is zero */ public static Vec<double[]> of(final double... array) { return new DoubleVec(array); } }
Improve Javadoc.
jenetics.ext/src/main/java/io/jenetics/ext/moea/Vec.java
Improve Javadoc.
<ide><path>enetics.ext/src/main/java/io/jenetics/ext/moea/Vec.java <ide> * final Vec<double[]> point2D = Vec.of(0.1, 5.4); <ide> * final Vec<int[]> point3D = Vec.of(1, 2, 3); <ide> * }</pre> <add> * <add> * The underlying array is <em>just</em> wrapped and <em>not</em> copied. This <add> * means you can change the values of the {@code Vec} once it is created, <add> * <em>Not copying the underlying array is done for performance reason. Changing <add> * the {@code Vec} data is, of course, never a good idea.</em> <ide> * <ide> * @implNote <ide> * Although the {@code Vec} interface extends the {@link Comparable} interface, <ide> * order. So, trying to sort a list of {@code Vec} objects, might lead <ide> * to an exception (thrown by the sorting method) at runtime. <ide> * <del> * @param <T> the underlying data type, like {@code int[]} or {@code double[]} <add> * @param <T> the underlying array type, like {@code int[]} or {@code double[]} <ide> * <ide> * @see <a href="https://en.wikipedia.org/wiki/Pareto_efficiency"> <ide> * Pareto efficiency</a>
Java
apache-2.0
62c832bb5763eb6712601596345113c866f008ab
0
jiangqqlmj/Android-Universal-Image-Loader-Modify
/******************************************************************************* * Copyright 2011-2014 Sergey Tarasevich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.nostra13.universalimageloader.core; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import com.nostra13.universalimageloader.cache.disc.DiskCache; import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.MemoryCache; import com.nostra13.universalimageloader.cache.memory.impl.FuzzyKeyMemoryCache; import com.nostra13.universalimageloader.core.assist.FlushedInputStream; import com.nostra13.universalimageloader.core.assist.ImageSize; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.decode.ImageDecoder; import com.nostra13.universalimageloader.core.download.ImageDownloader; import com.nostra13.universalimageloader.core.process.BitmapProcessor; import com.nostra13.universalimageloader.utils.L; import com.nostra13.universalimageloader.utils.MemoryCacheUtils; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; /** * ImageLoader参数配置类 * Presents configuration for {@link ImageLoader} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @see ImageLoader * @see MemoryCache * @see DiskCache * @see DisplayImageOptions * @see ImageDownloader * @see FileNameGenerator * @since 1.0.0 */ public final class ImageLoaderConfiguration { /*资源信息*/ final Resources resources; /*内存缓存 图片的最大宽度*/ final int maxImageWidthForMemoryCache; /*内存缓存 图片的最大高度*/ final int maxImageHeightForMemoryCache; /*本地文件系统缓存 图片的最大宽度*/ final int maxImageWidthForDiskCache; /*本地文件系统缓存 图片的最大高度*/ final int maxImageHeightForDiskCache; /*本地文件系统缓存 图片处理器*/ final BitmapProcessor processorForDiskCache; /*任务执行者*/ final Executor taskExecutor; /*图片缓存任务执行者*/ final Executor taskExecutorForCachedImages; /*是否为自定义任务执行者*/ final boolean customExecutor; /*是否为图片缓存自定义任务执行者*/ final boolean customExecutorForCachedImages; /*线程池中线程数量*/ final int threadPoolSize; /*线程等级*/ final int threadPriority; /*队列中处理算法类型*/ final QueueProcessingType tasksProcessingType; /*内存缓存对象*/ final MemoryCache memoryCache; /*本地文件系统缓存对象*/ final DiskCache diskCache; /*图片默认下载加载器*/ final ImageDownloader downloader; /*图片解码器*/ final ImageDecoder decoder; /*图片显示配置参数*/ final DisplayImageOptions defaultDisplayImageOptions; final ImageDownloader networkDeniedDownloader; final ImageDownloader slowNetworkDownloader; /** * ImageLoader参数配置构造器 把构建者中的数据 对全局变量初始化 * @param builder 构建信息对象 */ private ImageLoaderConfiguration(final Builder builder) { resources = builder.context.getResources(); maxImageWidthForMemoryCache = builder.maxImageWidthForMemoryCache; maxImageHeightForMemoryCache = builder.maxImageHeightForMemoryCache; maxImageWidthForDiskCache = builder.maxImageWidthForDiskCache; maxImageHeightForDiskCache = builder.maxImageHeightForDiskCache; processorForDiskCache = builder.processorForDiskCache; taskExecutor = builder.taskExecutor; taskExecutorForCachedImages = builder.taskExecutorForCachedImages; threadPoolSize = builder.threadPoolSize; threadPriority = builder.threadPriority; tasksProcessingType = builder.tasksProcessingType; diskCache = builder.diskCache; memoryCache = builder.memoryCache; defaultDisplayImageOptions = builder.defaultDisplayImageOptions; downloader = builder.downloader; decoder = builder.decoder; customExecutor = builder.customExecutor; customExecutorForCachedImages = builder.customExecutorForCachedImages; networkDeniedDownloader = new NetworkDeniedImageDownloader(downloader); slowNetworkDownloader = new SlowNetworkImageDownloader(downloader); L.writeDebugLogs(builder.writeLogs); } /** * 创建ImageLoader 默认的配置信息 * Creates default configuration for {@link ImageLoader} <br /> * <b>Default values:</b> * <ul> * <li>maxImageWidthForMemoryCache = device's screen width</li> * <li>maxImageHeightForMemoryCache = device's screen height</li> * <li>maxImageWidthForDikcCache = unlimited</li> * <li>maxImageHeightForDiskCache = unlimited</li> * <li>threadPoolSize = {@link Builder#DEFAULT_THREAD_POOL_SIZE this}</li> * <li>threadPriority = {@link Builder#DEFAULT_THREAD_PRIORITY this}</li> * <li>allow to cache different sizes of image in memory</li> * <li>memoryCache = {@link DefaultConfigurationFactory#createMemoryCache(android.content.Context, int)}</li> * <li>diskCache = {@link com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache}</li> * <li>imageDownloader = {@link DefaultConfigurationFactory#createImageDownloader(Context)}</li> * <li>imageDecoder = {@link DefaultConfigurationFactory#createImageDecoder(boolean)}</li> * <li>diskCacheFileNameGenerator = {@link DefaultConfigurationFactory#createFileNameGenerator()}</li> * <li>defaultDisplayImageOptions = {@link DisplayImageOptions#createSimple() Simple options}</li> * <li>tasksProcessingOrder = {@link QueueProcessingType#FIFO}</li> * <li>detailed logging disabled</li> * </ul> */ /** * 进行创建ImageLoader默认配置信息 * @param context * @return */ public static ImageLoaderConfiguration createDefault(Context context) { return new Builder(context).build(); } /** * 获取图片的最大尺寸信息-进行判断有没有配置maxImageWidthForMemoryCache和maxImageHeightForMemoryCache大小, * 如果没有那就采用屏幕的宽度或者高度 * @return 宽和高封装成ImageSize对象 */ ImageSize getMaxImageSize() { //获取屏幕信息 DisplayMetrics displayMetrics = resources.getDisplayMetrics(); int width = maxImageWidthForMemoryCache; if (width <= 0) { width = displayMetrics.widthPixels; } int height = maxImageHeightForMemoryCache; if (height <= 0) { height = displayMetrics.heightPixels; } return new ImageSize(width, height); } /** * Builder for {@link ImageLoaderConfiguration} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) */ public static class Builder { private static final String WARNING_OVERLAP_DISK_CACHE_PARAMS = "diskCache(), diskCacheSize() and diskCacheFileCount calls overlap each other"; private static final String WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR = "diskCache() and diskCacheFileNameGenerator() calls overlap each other"; private static final String WARNING_OVERLAP_MEMORY_CACHE = "memoryCache() and memoryCacheSize() calls overlap each other"; private static final String WARNING_OVERLAP_EXECUTOR = "threadPoolSize(), threadPriority() and tasksProcessingOrder() calls " + "can overlap taskExecutor() and taskExecutorForCachedImages() calls."; /** {@value} * 默认线程池中线程数量 */ public static final int DEFAULT_THREAD_POOL_SIZE = 3; /** {@value} * 线程权重等级 */ public static final int DEFAULT_THREAD_PRIORITY = Thread.NORM_PRIORITY - 2; /** {@value} * 队列文件处理算法类型 默认采用FIFO */ public static final QueueProcessingType DEFAULT_TASK_PROCESSING_TYPE = QueueProcessingType.FIFO; private Context context; //=============以下各种参数和顶部注释一样,不过这边已经给了相关的默认值================== private int maxImageWidthForMemoryCache = 0; private int maxImageHeightForMemoryCache = 0; private int maxImageWidthForDiskCache = 0; private int maxImageHeightForDiskCache = 0; private BitmapProcessor processorForDiskCache = null; private Executor taskExecutor = null; private Executor taskExecutorForCachedImages = null; private boolean customExecutor = false; private boolean customExecutorForCachedImages = false; private int threadPoolSize = DEFAULT_THREAD_POOL_SIZE; private int threadPriority = DEFAULT_THREAD_PRIORITY; private boolean denyCacheImageMultipleSizesInMemory = false; private QueueProcessingType tasksProcessingType = DEFAULT_TASK_PROCESSING_TYPE; private int memoryCacheSize = 0; private long diskCacheSize = 0; private int diskCacheFileCount = 0; private MemoryCache memoryCache = null; private DiskCache diskCache = null; private FileNameGenerator diskCacheFileNameGenerator = null; private ImageDownloader downloader = null; private ImageDecoder decoder; private DisplayImageOptions defaultDisplayImageOptions = null; private boolean writeLogs = false; /** * 构建器构造函数 * @param context */ public Builder(Context context) { this.context = context.getApplicationContext(); } /** * Sets options for memory cache * 进行配置内存缓存器的参数信息 图片最大宽度 以及 图片最大高度 * * @param maxImageWidthForMemoryCache Maximum image width which will be used for memory saving during decoding * an image to {@link android.graphics.Bitmap Bitmap}. <b>Default value - device's screen width</b> * @param maxImageHeightForMemoryCache Maximum image height which will be used for memory saving during decoding * an image to {@link android.graphics.Bitmap Bitmap}. <b>Default value</b> - device's screen height */ public Builder memoryCacheExtraOptions(int maxImageWidthForMemoryCache, int maxImageHeightForMemoryCache) { this.maxImageWidthForMemoryCache = maxImageWidthForMemoryCache; this.maxImageHeightForMemoryCache = maxImageHeightForMemoryCache; return this; } /** * @deprecated Use 该方法已经废弃使用 * {@link #diskCacheExtraOptions(int, int, com.nostra13.universalimageloader.core.process.BitmapProcessor)} * instead */ @Deprecated public Builder discCacheExtraOptions(int maxImageWidthForDiskCache, int maxImageHeightForDiskCache, BitmapProcessor processorForDiskCache) { return diskCacheExtraOptions(maxImageWidthForDiskCache, maxImageHeightForDiskCache, processorForDiskCache); } /** * 本地文件系统缓存图片的最大宽度和高度设置 * Sets options for resizing/compressing of downloaded images before saving to disk cache.<br /> * <b>NOTE: Use this option only when you have appropriate needs. It can make ImageLoader slower.</b> * * @param maxImageWidthForDiskCache Maximum width of downloaded images for saving at disk cache * @param maxImageHeightForDiskCache Maximum height of downloaded images for saving at disk cache * @param processorForDiskCache null-ok; {@linkplain BitmapProcessor Bitmap processor} which process images before saving them in disc cache */ public Builder diskCacheExtraOptions(int maxImageWidthForDiskCache, int maxImageHeightForDiskCache, BitmapProcessor processorForDiskCache) { this.maxImageWidthForDiskCache = maxImageWidthForDiskCache; this.maxImageHeightForDiskCache = maxImageHeightForDiskCache; this.processorForDiskCache = processorForDiskCache; return this; } /** * 设置图片加载和显示的自定义任务执行者 * Sets custom {@linkplain Executor executor} for tasks of loading and displaying images.<br /> * <br /> * <b>NOTE:</b> If you set custom executor then following configuration options will not be considered for this * executor: * <ul> * <li>{@link #threadPoolSize(int)}</li> * <li>{@link #threadPriority(int)}</li> * <li>{@link #tasksProcessingOrder(QueueProcessingType)}</li> * </ul> * * @see #taskExecutorForCachedImages(Executor) */ public Builder taskExecutor(Executor executor) { if (threadPoolSize != DEFAULT_THREAD_POOL_SIZE || threadPriority != DEFAULT_THREAD_PRIORITY || tasksProcessingType != DEFAULT_TASK_PROCESSING_TYPE) { L.w(WARNING_OVERLAP_EXECUTOR); } this.taskExecutor = executor; return this; } /** * 设置图片缓存自定义执行者 * Sets custom {@linkplain Executor executor} for tasks of displaying <b>cached on disk</b> images (these tasks * are executed quickly so UIL prefer to use separate executor for them).<br /> * <br /> * If you set the same executor for {@linkplain #taskExecutor(Executor) general tasks} and * tasks about cached images (this method) then these tasks will be in the * same thread pool. So short-lived tasks can wait a long time for their turn.<br /> * <br /> * <b>NOTE:</b> If you set custom executor then following configuration options will not be considered for this * executor: * <ul> * <li>{@link #threadPoolSize(int)}</li> * <li>{@link #threadPriority(int)}</li> * <li>{@link #tasksProcessingOrder(QueueProcessingType)}</li> * </ul> * @see #taskExecutor(Executor) */ public Builder taskExecutorForCachedImages(Executor executorForCachedImages) { if (threadPoolSize != DEFAULT_THREAD_POOL_SIZE || threadPriority != DEFAULT_THREAD_PRIORITY || tasksProcessingType != DEFAULT_TASK_PROCESSING_TYPE) { L.w(WARNING_OVERLAP_EXECUTOR); } this.taskExecutorForCachedImages = executorForCachedImages; return this; } /** * 设置图片显示线程池线程数量 * Sets thread pool size for image display tasks.<br /> * Default value - {@link #DEFAULT_THREAD_POOL_SIZE this} */ public Builder threadPoolSize(int threadPoolSize) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } this.threadPoolSize = threadPoolSize; return this; } /** * 设置图片加载线程权重等级 * Sets the priority for image loading threads. Should be <b>NOT</b> greater than {@link Thread#MAX_PRIORITY} or * less than {@link Thread#MIN_PRIORITY}<br /> * Default value - {@link #DEFAULT_THREAD_PRIORITY this} */ public Builder threadPriority(int threadPriority) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } if (threadPriority < Thread.MIN_PRIORITY) { this.threadPriority = Thread.MIN_PRIORITY; } else { if (threadPriority > Thread.MAX_PRIORITY) { this.threadPriority = Thread.MAX_PRIORITY; } else { this.threadPriority = threadPriority; } } return this; } /** * 设置是否需要内存中缓存多个尺寸的图片 * When you display an image in a small {@link android.widget.ImageView ImageView} and later you try to display * this image (from identical URI) in a larger {@link android.widget.ImageView ImageView} so decoded image of * bigger size will be cached in memory as a previous decoded image of smaller size.<br /> * So <b>the default behavior is to allow to cache multiple sizes of one image in memory</b>. You can * <b>deny</b> it by calling <b>this</b> method: so when some image will be cached in memory then previous * cached size of this image (if it exists) will be removed from memory cache before. */ public Builder denyCacheImageMultipleSizesInMemory() { this.denyCacheImageMultipleSizesInMemory = true; return this; } /** * 设置加载和显示图片任务的队列任务处理算法类型 * Sets type of queue processing for tasks for loading and displaying images.<br /> * Default value - {@link QueueProcessingType#FIFO} */ public Builder tasksProcessingOrder(QueueProcessingType tasksProcessingType) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } this.tasksProcessingType = tasksProcessingType; return this; } /** * 设置内存缓存器最大容量 * Sets maximum memory cache size for {@link android.graphics.Bitmap bitmaps} (in bytes).<br /> * Default value - 1/8 of available app memory.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} will be used as * memory cache. You can use {@link #memoryCache(MemoryCache)} method to set your own implementation of * {@link MemoryCache}. */ public Builder memoryCacheSize(int memoryCacheSize) { if (memoryCacheSize <= 0) throw new IllegalArgumentException("memoryCacheSize must be a positive number"); if (memoryCache != null) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } this.memoryCacheSize = memoryCacheSize; return this; } /** * 设置内存缓存器最大容量 所占APP 可获取内存的百分比 * Sets maximum memory cache size (in percent of available app memory) for {@link android.graphics.Bitmap * bitmaps}.<br /> * Default value - 1/8 of available app memory.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} will be used as * memory cache. You can use {@link #memoryCache(MemoryCache)} method to set your own implementation of * {@link MemoryCache}. */ public Builder memoryCacheSizePercentage(int availableMemoryPercent) { if (availableMemoryPercent <= 0 || availableMemoryPercent >= 100) { throw new IllegalArgumentException("availableMemoryPercent must be in range (0 < % < 100)"); } if (memoryCache != null) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } long availableMemory = Runtime.getRuntime().maxMemory(); memoryCacheSize = (int) (availableMemory * (availableMemoryPercent / 100f)); return this; } /** * 设置图片内存缓存器 * Sets memory cache for {@link android.graphics.Bitmap bitmaps}.<br /> * Default value - {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} * with limited memory cache size (size = 1/8 of available app memory)<br /> * <br /> * <b>NOTE:</b> If you set custom memory cache then following configuration option will not be considered: * <ul> * <li>{@link #memoryCacheSize(int)}</li> * </ul> */ public Builder memoryCache(MemoryCache memoryCache) { if (memoryCacheSize != 0) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } this.memoryCache = memoryCache; return this; } /** * @deprecated Use {@link #diskCacheSize(int)} instead * 废弃方法 */ @Deprecated public Builder discCacheSize(int maxCacheSize) { return diskCacheSize(maxCacheSize); } /** * 设置本地文件系统缓存器的大小 * Sets maximum disk cache size for images (in bytes).<br /> * By default: disk cache is unlimited.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache LruDiskCache} * will be used as disk cache. You can use {@link #diskCache(DiskCache)} method for introduction your own * implementation of {@link DiskCache} */ public Builder diskCacheSize(int maxCacheSize) { if (maxCacheSize <= 0) throw new IllegalArgumentException("maxCacheSize must be a positive number"); if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } this.diskCacheSize = maxCacheSize; return this; } /** * @deprecated Use {@link #diskCacheFileCount(int)} instead * 废弃方法 */ @Deprecated public Builder discCacheFileCount(int maxFileCount) { return diskCacheFileCount(maxFileCount); } /** * 设置本地文件缓存器中可缓存的文件大小 * Sets maximum file count in disk cache directory.<br /> * By default: disk cache is unlimited.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache LruDiskCache} * will be used as disk cache. You can use {@link #diskCache(DiskCache)} method for introduction your own * implementation of {@link DiskCache} */ public Builder diskCacheFileCount(int maxFileCount) { if (maxFileCount <= 0) throw new IllegalArgumentException("maxFileCount must be a positive number"); if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } this.diskCacheFileCount = maxFileCount; return this; } /** @deprecated Use {@link #diskCacheFileNameGenerator(com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator)} */ @Deprecated public Builder discCacheFileNameGenerator(FileNameGenerator fileNameGenerator) { return diskCacheFileNameGenerator(fileNameGenerator); } /** * 设置本地文件缓存器中 缓存文件名生成器 * Sets name generator for files cached in disk cache.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createFileNameGenerator() * DefaultConfigurationFactory.createFileNameGenerator()} */ public Builder diskCacheFileNameGenerator(FileNameGenerator fileNameGenerator) { if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR); } this.diskCacheFileNameGenerator = fileNameGenerator; return this; } /** @deprecated Use {@link #diskCache(com.nostra13.universalimageloader.cache.disc.DiskCache)} */ @Deprecated public Builder discCache(DiskCache diskCache) { return diskCache(diskCache); } /** * 设置本地文件系统缓存器 * Sets disk cache for images.<br /> * Default value - {@link com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache * UnlimitedDiskCache}. Cache directory is defined by * {@link com.nostra13.universalimageloader.utils.StorageUtils#getCacheDirectory(Context) * StorageUtils.getCacheDirectory(Context)}.<br /> * <br /> * <b>NOTE:</b> If you set custom disk cache then following configuration option will not be considered: * <ul> * <li>{@link #diskCacheSize(int)}</li> * <li>{@link #diskCacheFileCount(int)}</li> * <li>{@link #diskCacheFileNameGenerator(FileNameGenerator)}</li> * </ul> */ public Builder diskCache(DiskCache diskCache) { if (diskCacheSize > 0 || diskCacheFileCount > 0) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } if (diskCacheFileNameGenerator != null) { L.w(WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR); } this.diskCache = diskCache; return this; } /** * 设置图片下载器 * Sets utility which will be responsible for downloading of image.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDownloader(Context) * DefaultConfigurationFactory.createImageDownloader()} */ public Builder imageDownloader(ImageDownloader imageDownloader) { this.downloader = imageDownloader; return this; } /** * 设置图片解码器 * Sets utility which will be responsible for decoding of image stream.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDecoder(boolean) * DefaultConfigurationFactory.createImageDecoder()} */ public Builder imageDecoder(ImageDecoder imageDecoder) { this.decoder = imageDecoder; return this; } /** * Sets default {@linkplain DisplayImageOptions display image options} for image displaying. These options will * be used for every {@linkplain ImageLoader#displayImage(String, android.widget.ImageView) image display call} * without passing custom {@linkplain DisplayImageOptions options}<br /> * Default value - {@link DisplayImageOptions#createSimple() Simple options} */ public Builder defaultDisplayImageOptions(DisplayImageOptions defaultDisplayImageOptions) { this.defaultDisplayImageOptions = defaultDisplayImageOptions; return this; } /** * 设置开启运行日志 * Enables detail logging of {@link ImageLoader} work. To prevent detail logs don't call this method. * Consider {@link com.nostra13.universalimageloader.utils.L#disableLogging()} to disable * ImageLoader logging completely (even error logs) */ public Builder writeDebugLogs() { this.writeLogs = true; return this; } /** * Builds configured {@link ImageLoaderConfiguration} object * ImageLoader配置项 构建 */ public ImageLoaderConfiguration build() { initEmptyFieldsWithDefaultValues(); return new ImageLoaderConfiguration(this); } /** * 对于相关配置信息 进行默认初始化设置 */ private void initEmptyFieldsWithDefaultValues() { if (taskExecutor == null) { taskExecutor = DefaultConfigurationFactory .createExecutor(threadPoolSize, threadPriority, tasksProcessingType); } else { customExecutor = true; } if (taskExecutorForCachedImages == null) { taskExecutorForCachedImages = DefaultConfigurationFactory .createExecutor(threadPoolSize, threadPriority, tasksProcessingType); } else { customExecutorForCachedImages = true; } if (diskCache == null) { if (diskCacheFileNameGenerator == null) { diskCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator(); } diskCache = DefaultConfigurationFactory .createDiskCache(context, diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount); } if (memoryCache == null) { memoryCache = DefaultConfigurationFactory.createMemoryCache(context, memoryCacheSize); } if (denyCacheImageMultipleSizesInMemory) { memoryCache = new FuzzyKeyMemoryCache(memoryCache, MemoryCacheUtils.createFuzzyKeyComparator()); } if (downloader == null) { downloader = DefaultConfigurationFactory.createImageDownloader(context); } if (decoder == null) { decoder = DefaultConfigurationFactory.createImageDecoder(writeLogs); } if (defaultDisplayImageOptions == null) { defaultDisplayImageOptions = DisplayImageOptions.createSimple(); } } } /** * 下面是对于图片下载器的装饰封装的对象--网络拒绝访问的图片下载器 * Decorator. Prevents downloads from network (throws {@link IllegalStateException exception}).<br /> * In most cases this downloader shouldn't be used directly. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.0 */ private static class NetworkDeniedImageDownloader implements ImageDownloader { private final ImageDownloader wrappedDownloader; public NetworkDeniedImageDownloader(ImageDownloader wrappedDownloader) { this.wrappedDownloader = wrappedDownloader; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: throw new IllegalStateException(); default: return wrappedDownloader.getStream(imageUri, extra); } } } /** * 下面是对于图片下载器的装饰封装的对象--网络访问速度慢的图片下载器 * Decorator. Handles <a href="http://code.google.com/p/android/issues/detail?id=6066">this problem</a> on slow networks * using {@link com.nostra13.universalimageloader.core.assist.FlushedInputStream}. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.1 */ private static class SlowNetworkImageDownloader implements ImageDownloader { private final ImageDownloader wrappedDownloader; public SlowNetworkImageDownloader(ImageDownloader wrappedDownloader) { this.wrappedDownloader = wrappedDownloader; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { InputStream imageStream = wrappedDownloader.getStream(imageUri, extra); switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: return new FlushedInputStream(imageStream); default: return imageStream; } } } }
library/src/main/java/com/nostra13/universalimageloader/core/ImageLoaderConfiguration.java
/******************************************************************************* * Copyright 2011-2014 Sergey Tarasevich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.nostra13.universalimageloader.core; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import com.nostra13.universalimageloader.cache.disc.DiskCache; import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.MemoryCache; import com.nostra13.universalimageloader.cache.memory.impl.FuzzyKeyMemoryCache; import com.nostra13.universalimageloader.core.assist.FlushedInputStream; import com.nostra13.universalimageloader.core.assist.ImageSize; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.decode.ImageDecoder; import com.nostra13.universalimageloader.core.download.ImageDownloader; import com.nostra13.universalimageloader.core.process.BitmapProcessor; import com.nostra13.universalimageloader.utils.L; import com.nostra13.universalimageloader.utils.MemoryCacheUtils; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; /** * Presents configuration for {@link ImageLoader} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @see ImageLoader * @see MemoryCache * @see DiskCache * @see DisplayImageOptions * @see ImageDownloader * @see FileNameGenerator * @since 1.0.0 */ public final class ImageLoaderConfiguration { final Resources resources; final int maxImageWidthForMemoryCache; final int maxImageHeightForMemoryCache; final int maxImageWidthForDiskCache; final int maxImageHeightForDiskCache; final BitmapProcessor processorForDiskCache; final Executor taskExecutor; final Executor taskExecutorForCachedImages; final boolean customExecutor; final boolean customExecutorForCachedImages; final int threadPoolSize; final int threadPriority; final QueueProcessingType tasksProcessingType; final MemoryCache memoryCache; final DiskCache diskCache; final ImageDownloader downloader; final ImageDecoder decoder; final DisplayImageOptions defaultDisplayImageOptions; final ImageDownloader networkDeniedDownloader; final ImageDownloader slowNetworkDownloader; private ImageLoaderConfiguration(final Builder builder) { resources = builder.context.getResources(); maxImageWidthForMemoryCache = builder.maxImageWidthForMemoryCache; maxImageHeightForMemoryCache = builder.maxImageHeightForMemoryCache; maxImageWidthForDiskCache = builder.maxImageWidthForDiskCache; maxImageHeightForDiskCache = builder.maxImageHeightForDiskCache; processorForDiskCache = builder.processorForDiskCache; taskExecutor = builder.taskExecutor; taskExecutorForCachedImages = builder.taskExecutorForCachedImages; threadPoolSize = builder.threadPoolSize; threadPriority = builder.threadPriority; tasksProcessingType = builder.tasksProcessingType; diskCache = builder.diskCache; memoryCache = builder.memoryCache; defaultDisplayImageOptions = builder.defaultDisplayImageOptions; downloader = builder.downloader; decoder = builder.decoder; customExecutor = builder.customExecutor; customExecutorForCachedImages = builder.customExecutorForCachedImages; networkDeniedDownloader = new NetworkDeniedImageDownloader(downloader); slowNetworkDownloader = new SlowNetworkImageDownloader(downloader); L.writeDebugLogs(builder.writeLogs); } /** * Creates default configuration for {@link ImageLoader} <br /> * <b>Default values:</b> * <ul> * <li>maxImageWidthForMemoryCache = device's screen width</li> * <li>maxImageHeightForMemoryCache = device's screen height</li> * <li>maxImageWidthForDikcCache = unlimited</li> * <li>maxImageHeightForDiskCache = unlimited</li> * <li>threadPoolSize = {@link Builder#DEFAULT_THREAD_POOL_SIZE this}</li> * <li>threadPriority = {@link Builder#DEFAULT_THREAD_PRIORITY this}</li> * <li>allow to cache different sizes of image in memory</li> * <li>memoryCache = {@link DefaultConfigurationFactory#createMemoryCache(android.content.Context, int)}</li> * <li>diskCache = {@link com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache}</li> * <li>imageDownloader = {@link DefaultConfigurationFactory#createImageDownloader(Context)}</li> * <li>imageDecoder = {@link DefaultConfigurationFactory#createImageDecoder(boolean)}</li> * <li>diskCacheFileNameGenerator = {@link DefaultConfigurationFactory#createFileNameGenerator()}</li> * <li>defaultDisplayImageOptions = {@link DisplayImageOptions#createSimple() Simple options}</li> * <li>tasksProcessingOrder = {@link QueueProcessingType#FIFO}</li> * <li>detailed logging disabled</li> * </ul> */ public static ImageLoaderConfiguration createDefault(Context context) { return new Builder(context).build(); } ImageSize getMaxImageSize() { DisplayMetrics displayMetrics = resources.getDisplayMetrics(); int width = maxImageWidthForMemoryCache; if (width <= 0) { width = displayMetrics.widthPixels; } int height = maxImageHeightForMemoryCache; if (height <= 0) { height = displayMetrics.heightPixels; } return new ImageSize(width, height); } /** * Builder for {@link ImageLoaderConfiguration} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) */ public static class Builder { private static final String WARNING_OVERLAP_DISK_CACHE_PARAMS = "diskCache(), diskCacheSize() and diskCacheFileCount calls overlap each other"; private static final String WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR = "diskCache() and diskCacheFileNameGenerator() calls overlap each other"; private static final String WARNING_OVERLAP_MEMORY_CACHE = "memoryCache() and memoryCacheSize() calls overlap each other"; private static final String WARNING_OVERLAP_EXECUTOR = "threadPoolSize(), threadPriority() and tasksProcessingOrder() calls " + "can overlap taskExecutor() and taskExecutorForCachedImages() calls."; /** {@value} */ public static final int DEFAULT_THREAD_POOL_SIZE = 3; /** {@value} */ public static final int DEFAULT_THREAD_PRIORITY = Thread.NORM_PRIORITY - 2; /** {@value} */ public static final QueueProcessingType DEFAULT_TASK_PROCESSING_TYPE = QueueProcessingType.FIFO; private Context context; private int maxImageWidthForMemoryCache = 0; private int maxImageHeightForMemoryCache = 0; private int maxImageWidthForDiskCache = 0; private int maxImageHeightForDiskCache = 0; private BitmapProcessor processorForDiskCache = null; private Executor taskExecutor = null; private Executor taskExecutorForCachedImages = null; private boolean customExecutor = false; private boolean customExecutorForCachedImages = false; private int threadPoolSize = DEFAULT_THREAD_POOL_SIZE; private int threadPriority = DEFAULT_THREAD_PRIORITY; private boolean denyCacheImageMultipleSizesInMemory = false; private QueueProcessingType tasksProcessingType = DEFAULT_TASK_PROCESSING_TYPE; private int memoryCacheSize = 0; private long diskCacheSize = 0; private int diskCacheFileCount = 0; private MemoryCache memoryCache = null; private DiskCache diskCache = null; private FileNameGenerator diskCacheFileNameGenerator = null; private ImageDownloader downloader = null; private ImageDecoder decoder; private DisplayImageOptions defaultDisplayImageOptions = null; private boolean writeLogs = false; public Builder(Context context) { this.context = context.getApplicationContext(); } /** * Sets options for memory cache * * @param maxImageWidthForMemoryCache Maximum image width which will be used for memory saving during decoding * an image to {@link android.graphics.Bitmap Bitmap}. <b>Default value - device's screen width</b> * @param maxImageHeightForMemoryCache Maximum image height which will be used for memory saving during decoding * an image to {@link android.graphics.Bitmap Bitmap}. <b>Default value</b> - device's screen height */ public Builder memoryCacheExtraOptions(int maxImageWidthForMemoryCache, int maxImageHeightForMemoryCache) { this.maxImageWidthForMemoryCache = maxImageWidthForMemoryCache; this.maxImageHeightForMemoryCache = maxImageHeightForMemoryCache; return this; } /** * @deprecated Use * {@link #diskCacheExtraOptions(int, int, com.nostra13.universalimageloader.core.process.BitmapProcessor)} * instead */ @Deprecated public Builder discCacheExtraOptions(int maxImageWidthForDiskCache, int maxImageHeightForDiskCache, BitmapProcessor processorForDiskCache) { return diskCacheExtraOptions(maxImageWidthForDiskCache, maxImageHeightForDiskCache, processorForDiskCache); } /** * Sets options for resizing/compressing of downloaded images before saving to disk cache.<br /> * <b>NOTE: Use this option only when you have appropriate needs. It can make ImageLoader slower.</b> * * @param maxImageWidthForDiskCache Maximum width of downloaded images for saving at disk cache * @param maxImageHeightForDiskCache Maximum height of downloaded images for saving at disk cache * @param processorForDiskCache null-ok; {@linkplain BitmapProcessor Bitmap processor} which process images before saving them in disc cache */ public Builder diskCacheExtraOptions(int maxImageWidthForDiskCache, int maxImageHeightForDiskCache, BitmapProcessor processorForDiskCache) { this.maxImageWidthForDiskCache = maxImageWidthForDiskCache; this.maxImageHeightForDiskCache = maxImageHeightForDiskCache; this.processorForDiskCache = processorForDiskCache; return this; } /** * Sets custom {@linkplain Executor executor} for tasks of loading and displaying images.<br /> * <br /> * <b>NOTE:</b> If you set custom executor then following configuration options will not be considered for this * executor: * <ul> * <li>{@link #threadPoolSize(int)}</li> * <li>{@link #threadPriority(int)}</li> * <li>{@link #tasksProcessingOrder(QueueProcessingType)}</li> * </ul> * * @see #taskExecutorForCachedImages(Executor) */ public Builder taskExecutor(Executor executor) { if (threadPoolSize != DEFAULT_THREAD_POOL_SIZE || threadPriority != DEFAULT_THREAD_PRIORITY || tasksProcessingType != DEFAULT_TASK_PROCESSING_TYPE) { L.w(WARNING_OVERLAP_EXECUTOR); } this.taskExecutor = executor; return this; } /** * Sets custom {@linkplain Executor executor} for tasks of displaying <b>cached on disk</b> images (these tasks * are executed quickly so UIL prefer to use separate executor for them).<br /> * <br /> * If you set the same executor for {@linkplain #taskExecutor(Executor) general tasks} and * tasks about cached images (this method) then these tasks will be in the * same thread pool. So short-lived tasks can wait a long time for their turn.<br /> * <br /> * <b>NOTE:</b> If you set custom executor then following configuration options will not be considered for this * executor: * <ul> * <li>{@link #threadPoolSize(int)}</li> * <li>{@link #threadPriority(int)}</li> * <li>{@link #tasksProcessingOrder(QueueProcessingType)}</li> * </ul> * * @see #taskExecutor(Executor) */ public Builder taskExecutorForCachedImages(Executor executorForCachedImages) { if (threadPoolSize != DEFAULT_THREAD_POOL_SIZE || threadPriority != DEFAULT_THREAD_PRIORITY || tasksProcessingType != DEFAULT_TASK_PROCESSING_TYPE) { L.w(WARNING_OVERLAP_EXECUTOR); } this.taskExecutorForCachedImages = executorForCachedImages; return this; } /** * Sets thread pool size for image display tasks.<br /> * Default value - {@link #DEFAULT_THREAD_POOL_SIZE this} */ public Builder threadPoolSize(int threadPoolSize) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } this.threadPoolSize = threadPoolSize; return this; } /** * Sets the priority for image loading threads. Should be <b>NOT</b> greater than {@link Thread#MAX_PRIORITY} or * less than {@link Thread#MIN_PRIORITY}<br /> * Default value - {@link #DEFAULT_THREAD_PRIORITY this} */ public Builder threadPriority(int threadPriority) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } if (threadPriority < Thread.MIN_PRIORITY) { this.threadPriority = Thread.MIN_PRIORITY; } else { if (threadPriority > Thread.MAX_PRIORITY) { this.threadPriority = Thread.MAX_PRIORITY; } else { this.threadPriority = threadPriority; } } return this; } /** * When you display an image in a small {@link android.widget.ImageView ImageView} and later you try to display * this image (from identical URI) in a larger {@link android.widget.ImageView ImageView} so decoded image of * bigger size will be cached in memory as a previous decoded image of smaller size.<br /> * So <b>the default behavior is to allow to cache multiple sizes of one image in memory</b>. You can * <b>deny</b> it by calling <b>this</b> method: so when some image will be cached in memory then previous * cached size of this image (if it exists) will be removed from memory cache before. */ public Builder denyCacheImageMultipleSizesInMemory() { this.denyCacheImageMultipleSizesInMemory = true; return this; } /** * Sets type of queue processing for tasks for loading and displaying images.<br /> * Default value - {@link QueueProcessingType#FIFO} */ public Builder tasksProcessingOrder(QueueProcessingType tasksProcessingType) { if (taskExecutor != null || taskExecutorForCachedImages != null) { L.w(WARNING_OVERLAP_EXECUTOR); } this.tasksProcessingType = tasksProcessingType; return this; } /** * Sets maximum memory cache size for {@link android.graphics.Bitmap bitmaps} (in bytes).<br /> * Default value - 1/8 of available app memory.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} will be used as * memory cache. You can use {@link #memoryCache(MemoryCache)} method to set your own implementation of * {@link MemoryCache}. */ public Builder memoryCacheSize(int memoryCacheSize) { if (memoryCacheSize <= 0) throw new IllegalArgumentException("memoryCacheSize must be a positive number"); if (memoryCache != null) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } this.memoryCacheSize = memoryCacheSize; return this; } /** * Sets maximum memory cache size (in percent of available app memory) for {@link android.graphics.Bitmap * bitmaps}.<br /> * Default value - 1/8 of available app memory.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} will be used as * memory cache. You can use {@link #memoryCache(MemoryCache)} method to set your own implementation of * {@link MemoryCache}. */ public Builder memoryCacheSizePercentage(int availableMemoryPercent) { if (availableMemoryPercent <= 0 || availableMemoryPercent >= 100) { throw new IllegalArgumentException("availableMemoryPercent must be in range (0 < % < 100)"); } if (memoryCache != null) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } long availableMemory = Runtime.getRuntime().maxMemory(); memoryCacheSize = (int) (availableMemory * (availableMemoryPercent / 100f)); return this; } /** * Sets memory cache for {@link android.graphics.Bitmap bitmaps}.<br /> * Default value - {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} * with limited memory cache size (size = 1/8 of available app memory)<br /> * <br /> * <b>NOTE:</b> If you set custom memory cache then following configuration option will not be considered: * <ul> * <li>{@link #memoryCacheSize(int)}</li> * </ul> */ public Builder memoryCache(MemoryCache memoryCache) { if (memoryCacheSize != 0) { L.w(WARNING_OVERLAP_MEMORY_CACHE); } this.memoryCache = memoryCache; return this; } /** @deprecated Use {@link #diskCacheSize(int)} instead */ @Deprecated public Builder discCacheSize(int maxCacheSize) { return diskCacheSize(maxCacheSize); } /** * Sets maximum disk cache size for images (in bytes).<br /> * By default: disk cache is unlimited.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache LruDiskCache} * will be used as disk cache. You can use {@link #diskCache(DiskCache)} method for introduction your own * implementation of {@link DiskCache} */ public Builder diskCacheSize(int maxCacheSize) { if (maxCacheSize <= 0) throw new IllegalArgumentException("maxCacheSize must be a positive number"); if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } this.diskCacheSize = maxCacheSize; return this; } /** @deprecated Use {@link #diskCacheFileCount(int)} instead */ @Deprecated public Builder discCacheFileCount(int maxFileCount) { return diskCacheFileCount(maxFileCount); } /** * Sets maximum file count in disk cache directory.<br /> * By default: disk cache is unlimited.<br /> * <b>NOTE:</b> If you use this method then * {@link com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache LruDiskCache} * will be used as disk cache. You can use {@link #diskCache(DiskCache)} method for introduction your own * implementation of {@link DiskCache} */ public Builder diskCacheFileCount(int maxFileCount) { if (maxFileCount <= 0) throw new IllegalArgumentException("maxFileCount must be a positive number"); if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } this.diskCacheFileCount = maxFileCount; return this; } /** @deprecated Use {@link #diskCacheFileNameGenerator(com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator)} */ @Deprecated public Builder discCacheFileNameGenerator(FileNameGenerator fileNameGenerator) { return diskCacheFileNameGenerator(fileNameGenerator); } /** * Sets name generator for files cached in disk cache.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createFileNameGenerator() * DefaultConfigurationFactory.createFileNameGenerator()} */ public Builder diskCacheFileNameGenerator(FileNameGenerator fileNameGenerator) { if (diskCache != null) { L.w(WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR); } this.diskCacheFileNameGenerator = fileNameGenerator; return this; } /** @deprecated Use {@link #diskCache(com.nostra13.universalimageloader.cache.disc.DiskCache)} */ @Deprecated public Builder discCache(DiskCache diskCache) { return diskCache(diskCache); } /** * Sets disk cache for images.<br /> * Default value - {@link com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache * UnlimitedDiskCache}. Cache directory is defined by * {@link com.nostra13.universalimageloader.utils.StorageUtils#getCacheDirectory(Context) * StorageUtils.getCacheDirectory(Context)}.<br /> * <br /> * <b>NOTE:</b> If you set custom disk cache then following configuration option will not be considered: * <ul> * <li>{@link #diskCacheSize(int)}</li> * <li>{@link #diskCacheFileCount(int)}</li> * <li>{@link #diskCacheFileNameGenerator(FileNameGenerator)}</li> * </ul> */ public Builder diskCache(DiskCache diskCache) { if (diskCacheSize > 0 || diskCacheFileCount > 0) { L.w(WARNING_OVERLAP_DISK_CACHE_PARAMS); } if (diskCacheFileNameGenerator != null) { L.w(WARNING_OVERLAP_DISK_CACHE_NAME_GENERATOR); } this.diskCache = diskCache; return this; } /** * Sets utility which will be responsible for downloading of image.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDownloader(Context) * DefaultConfigurationFactory.createImageDownloader()} */ public Builder imageDownloader(ImageDownloader imageDownloader) { this.downloader = imageDownloader; return this; } /** * Sets utility which will be responsible for decoding of image stream.<br /> * Default value - * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDecoder(boolean) * DefaultConfigurationFactory.createImageDecoder()} */ public Builder imageDecoder(ImageDecoder imageDecoder) { this.decoder = imageDecoder; return this; } /** * Sets default {@linkplain DisplayImageOptions display image options} for image displaying. These options will * be used for every {@linkplain ImageLoader#displayImage(String, android.widget.ImageView) image display call} * without passing custom {@linkplain DisplayImageOptions options}<br /> * Default value - {@link DisplayImageOptions#createSimple() Simple options} */ public Builder defaultDisplayImageOptions(DisplayImageOptions defaultDisplayImageOptions) { this.defaultDisplayImageOptions = defaultDisplayImageOptions; return this; } /** * Enables detail logging of {@link ImageLoader} work. To prevent detail logs don't call this method. * Consider {@link com.nostra13.universalimageloader.utils.L#disableLogging()} to disable * ImageLoader logging completely (even error logs) */ public Builder writeDebugLogs() { this.writeLogs = true; return this; } /** Builds configured {@link ImageLoaderConfiguration} object */ public ImageLoaderConfiguration build() { initEmptyFieldsWithDefaultValues(); return new ImageLoaderConfiguration(this); } private void initEmptyFieldsWithDefaultValues() { if (taskExecutor == null) { taskExecutor = DefaultConfigurationFactory .createExecutor(threadPoolSize, threadPriority, tasksProcessingType); } else { customExecutor = true; } if (taskExecutorForCachedImages == null) { taskExecutorForCachedImages = DefaultConfigurationFactory .createExecutor(threadPoolSize, threadPriority, tasksProcessingType); } else { customExecutorForCachedImages = true; } if (diskCache == null) { if (diskCacheFileNameGenerator == null) { diskCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator(); } diskCache = DefaultConfigurationFactory .createDiskCache(context, diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount); } if (memoryCache == null) { memoryCache = DefaultConfigurationFactory.createMemoryCache(context, memoryCacheSize); } if (denyCacheImageMultipleSizesInMemory) { memoryCache = new FuzzyKeyMemoryCache(memoryCache, MemoryCacheUtils.createFuzzyKeyComparator()); } if (downloader == null) { downloader = DefaultConfigurationFactory.createImageDownloader(context); } if (decoder == null) { decoder = DefaultConfigurationFactory.createImageDecoder(writeLogs); } if (defaultDisplayImageOptions == null) { defaultDisplayImageOptions = DisplayImageOptions.createSimple(); } } } /** * Decorator. Prevents downloads from network (throws {@link IllegalStateException exception}).<br /> * In most cases this downloader shouldn't be used directly. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.0 */ private static class NetworkDeniedImageDownloader implements ImageDownloader { private final ImageDownloader wrappedDownloader; public NetworkDeniedImageDownloader(ImageDownloader wrappedDownloader) { this.wrappedDownloader = wrappedDownloader; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: throw new IllegalStateException(); default: return wrappedDownloader.getStream(imageUri, extra); } } } /** * Decorator. Handles <a href="http://code.google.com/p/android/issues/detail?id=6066">this problem</a> on slow networks * using {@link com.nostra13.universalimageloader.core.assist.FlushedInputStream}. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.1 */ private static class SlowNetworkImageDownloader implements ImageDownloader { private final ImageDownloader wrappedDownloader; public SlowNetworkImageDownloader(ImageDownloader wrappedDownloader) { this.wrappedDownloader = wrappedDownloader; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { InputStream imageStream = wrappedDownloader.getStream(imageUri, extra); switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: return new FlushedInputStream(imageStream); default: return imageStream; } } } }
+):1.完成ImageLoaderConfiguration ImageLoader参数配置类和方法的注释
library/src/main/java/com/nostra13/universalimageloader/core/ImageLoaderConfiguration.java
+):1.完成ImageLoaderConfiguration ImageLoader参数配置类和方法的注释
<ide><path>ibrary/src/main/java/com/nostra13/universalimageloader/core/ImageLoaderConfiguration.java <ide> import java.util.concurrent.Executor; <ide> <ide> /** <add> * ImageLoader参数配置类 <ide> * Presents configuration for {@link ImageLoader} <ide> * <ide> * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) <ide> * @since 1.0.0 <ide> */ <ide> public final class ImageLoaderConfiguration { <del> <add> /*资源信息*/ <ide> final Resources resources; <del> <add> /*内存缓存 图片的最大宽度*/ <ide> final int maxImageWidthForMemoryCache; <add> /*内存缓存 图片的最大高度*/ <ide> final int maxImageHeightForMemoryCache; <add> /*本地文件系统缓存 图片的最大宽度*/ <ide> final int maxImageWidthForDiskCache; <add> /*本地文件系统缓存 图片的最大高度*/ <ide> final int maxImageHeightForDiskCache; <add> /*本地文件系统缓存 图片处理器*/ <ide> final BitmapProcessor processorForDiskCache; <del> <add> /*任务执行者*/ <ide> final Executor taskExecutor; <add> /*图片缓存任务执行者*/ <ide> final Executor taskExecutorForCachedImages; <add> /*是否为自定义任务执行者*/ <ide> final boolean customExecutor; <add> /*是否为图片缓存自定义任务执行者*/ <ide> final boolean customExecutorForCachedImages; <del> <add> /*线程池中线程数量*/ <ide> final int threadPoolSize; <add> /*线程等级*/ <ide> final int threadPriority; <add> /*队列中处理算法类型*/ <ide> final QueueProcessingType tasksProcessingType; <del> <add> /*内存缓存对象*/ <ide> final MemoryCache memoryCache; <add> /*本地文件系统缓存对象*/ <ide> final DiskCache diskCache; <add> /*图片默认下载加载器*/ <ide> final ImageDownloader downloader; <add> /*图片解码器*/ <ide> final ImageDecoder decoder; <add> /*图片显示配置参数*/ <ide> final DisplayImageOptions defaultDisplayImageOptions; <ide> <ide> final ImageDownloader networkDeniedDownloader; <ide> final ImageDownloader slowNetworkDownloader; <ide> <add> /** <add> * ImageLoader参数配置构造器 把构建者中的数据 对全局变量初始化 <add> * @param builder 构建信息对象 <add> */ <ide> private ImageLoaderConfiguration(final Builder builder) { <ide> resources = builder.context.getResources(); <ide> maxImageWidthForMemoryCache = builder.maxImageWidthForMemoryCache; <ide> } <ide> <ide> /** <add> * 创建ImageLoader 默认的配置信息 <ide> * Creates default configuration for {@link ImageLoader} <br /> <ide> * <b>Default values:</b> <ide> * <ul> <ide> * <li>detailed logging disabled</li> <ide> * </ul> <ide> */ <add> /** <add> * 进行创建ImageLoader默认配置信息 <add> * @param context <add> * @return <add> */ <ide> public static ImageLoaderConfiguration createDefault(Context context) { <ide> return new Builder(context).build(); <ide> } <ide> <add> /** <add> * 获取图片的最大尺寸信息-进行判断有没有配置maxImageWidthForMemoryCache和maxImageHeightForMemoryCache大小, <add> * 如果没有那就采用屏幕的宽度或者高度 <add> * @return 宽和高封装成ImageSize对象 <add> */ <ide> ImageSize getMaxImageSize() { <add> //获取屏幕信息 <ide> DisplayMetrics displayMetrics = resources.getDisplayMetrics(); <ide> <ide> int width = maxImageWidthForMemoryCache; <ide> private static final String WARNING_OVERLAP_EXECUTOR = "threadPoolSize(), threadPriority() and tasksProcessingOrder() calls " <ide> + "can overlap taskExecutor() and taskExecutorForCachedImages() calls."; <ide> <del> /** {@value} */ <add> /** {@value} <add> * 默认线程池中线程数量 <add> */ <ide> public static final int DEFAULT_THREAD_POOL_SIZE = 3; <del> /** {@value} */ <add> /** {@value} <add> * 线程权重等级 <add> */ <ide> public static final int DEFAULT_THREAD_PRIORITY = Thread.NORM_PRIORITY - 2; <del> /** {@value} */ <add> /** {@value} <add> * 队列文件处理算法类型 默认采用FIFO <add> */ <ide> public static final QueueProcessingType DEFAULT_TASK_PROCESSING_TYPE = QueueProcessingType.FIFO; <ide> <ide> private Context context; <del> <add> //=============以下各种参数和顶部注释一样,不过这边已经给了相关的默认值================== <ide> private int maxImageWidthForMemoryCache = 0; <ide> private int maxImageHeightForMemoryCache = 0; <ide> private int maxImageWidthForDiskCache = 0; <ide> <ide> private boolean writeLogs = false; <ide> <add> /** <add> * 构建器构造函数 <add> * @param context <add> */ <ide> public Builder(Context context) { <ide> this.context = context.getApplicationContext(); <ide> } <ide> <ide> /** <ide> * Sets options for memory cache <add> * 进行配置内存缓存器的参数信息 图片最大宽度 以及 图片最大高度 <ide> * <ide> * @param maxImageWidthForMemoryCache Maximum image width which will be used for memory saving during decoding <ide> * an image to {@link android.graphics.Bitmap Bitmap}. <b>Default value - device's screen width</b> <ide> } <ide> <ide> /** <del> * @deprecated Use <add> * @deprecated Use 该方法已经废弃使用 <ide> * {@link #diskCacheExtraOptions(int, int, com.nostra13.universalimageloader.core.process.BitmapProcessor)} <ide> * instead <ide> */ <ide> } <ide> <ide> /** <add> * 本地文件系统缓存图片的最大宽度和高度设置 <ide> * Sets options for resizing/compressing of downloaded images before saving to disk cache.<br /> <ide> * <b>NOTE: Use this option only when you have appropriate needs. It can make ImageLoader slower.</b> <ide> * <ide> } <ide> <ide> /** <add> * 设置图片加载和显示的自定义任务执行者 <ide> * Sets custom {@linkplain Executor executor} for tasks of loading and displaying images.<br /> <ide> * <br /> <ide> * <b>NOTE:</b> If you set custom executor then following configuration options will not be considered for this <ide> } <ide> <ide> /** <add> * 设置图片缓存自定义执行者 <ide> * Sets custom {@linkplain Executor executor} for tasks of displaying <b>cached on disk</b> images (these tasks <ide> * are executed quickly so UIL prefer to use separate executor for them).<br /> <ide> * <br /> <ide> * <li>{@link #threadPriority(int)}</li> <ide> * <li>{@link #tasksProcessingOrder(QueueProcessingType)}</li> <ide> * </ul> <del> * <ide> * @see #taskExecutor(Executor) <ide> */ <ide> public Builder taskExecutorForCachedImages(Executor executorForCachedImages) { <ide> } <ide> <ide> /** <add> * 设置图片显示线程池线程数量 <ide> * Sets thread pool size for image display tasks.<br /> <ide> * Default value - {@link #DEFAULT_THREAD_POOL_SIZE this} <ide> */ <ide> } <ide> <ide> /** <add> * 设置图片加载线程权重等级 <ide> * Sets the priority for image loading threads. Should be <b>NOT</b> greater than {@link Thread#MAX_PRIORITY} or <ide> * less than {@link Thread#MIN_PRIORITY}<br /> <ide> * Default value - {@link #DEFAULT_THREAD_PRIORITY this} <ide> } <ide> <ide> /** <add> * 设置是否需要内存中缓存多个尺寸的图片 <ide> * When you display an image in a small {@link android.widget.ImageView ImageView} and later you try to display <ide> * this image (from identical URI) in a larger {@link android.widget.ImageView ImageView} so decoded image of <ide> * bigger size will be cached in memory as a previous decoded image of smaller size.<br /> <ide> } <ide> <ide> /** <add> * 设置加载和显示图片任务的队列任务处理算法类型 <ide> * Sets type of queue processing for tasks for loading and displaying images.<br /> <ide> * Default value - {@link QueueProcessingType#FIFO} <ide> */ <ide> } <ide> <ide> /** <add> * 设置内存缓存器最大容量 <ide> * Sets maximum memory cache size for {@link android.graphics.Bitmap bitmaps} (in bytes).<br /> <ide> * Default value - 1/8 of available app memory.<br /> <ide> * <b>NOTE:</b> If you use this method then <ide> } <ide> <ide> /** <add> * 设置内存缓存器最大容量 所占APP 可获取内存的百分比 <ide> * Sets maximum memory cache size (in percent of available app memory) for {@link android.graphics.Bitmap <ide> * bitmaps}.<br /> <ide> * Default value - 1/8 of available app memory.<br /> <ide> } <ide> <ide> /** <add> * 设置图片内存缓存器 <ide> * Sets memory cache for {@link android.graphics.Bitmap bitmaps}.<br /> <ide> * Default value - {@link com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache LruMemoryCache} <ide> * with limited memory cache size (size = 1/8 of available app memory)<br /> <ide> return this; <ide> } <ide> <del> /** @deprecated Use {@link #diskCacheSize(int)} instead */ <add> /** <add> * @deprecated Use {@link #diskCacheSize(int)} instead <add> * 废弃方法 <add> */ <ide> @Deprecated <ide> public Builder discCacheSize(int maxCacheSize) { <ide> return diskCacheSize(maxCacheSize); <ide> } <ide> <ide> /** <add> * 设置本地文件系统缓存器的大小 <ide> * Sets maximum disk cache size for images (in bytes).<br /> <ide> * By default: disk cache is unlimited.<br /> <ide> * <b>NOTE:</b> If you use this method then <ide> return this; <ide> } <ide> <del> /** @deprecated Use {@link #diskCacheFileCount(int)} instead */ <add> /** <add> * @deprecated Use {@link #diskCacheFileCount(int)} instead <add> * 废弃方法 <add> */ <ide> @Deprecated <ide> public Builder discCacheFileCount(int maxFileCount) { <ide> return diskCacheFileCount(maxFileCount); <ide> } <ide> <ide> /** <add> * 设置本地文件缓存器中可缓存的文件大小 <ide> * Sets maximum file count in disk cache directory.<br /> <ide> * By default: disk cache is unlimited.<br /> <ide> * <b>NOTE:</b> If you use this method then <ide> } <ide> <ide> /** <add> * 设置本地文件缓存器中 缓存文件名生成器 <ide> * Sets name generator for files cached in disk cache.<br /> <ide> * Default value - <ide> * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createFileNameGenerator() <ide> } <ide> <ide> /** <add> * 设置本地文件系统缓存器 <ide> * Sets disk cache for images.<br /> <ide> * Default value - {@link com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache <ide> * UnlimitedDiskCache}. Cache directory is defined by <ide> } <ide> <ide> /** <add> * 设置图片下载器 <ide> * Sets utility which will be responsible for downloading of image.<br /> <ide> * Default value - <ide> * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDownloader(Context) <ide> } <ide> <ide> /** <add> * 设置图片解码器 <ide> * Sets utility which will be responsible for decoding of image stream.<br /> <ide> * Default value - <ide> * {@link com.nostra13.universalimageloader.core.DefaultConfigurationFactory#createImageDecoder(boolean) <ide> } <ide> <ide> /** <add> * 设置开启运行日志 <ide> * Enables detail logging of {@link ImageLoader} work. To prevent detail logs don't call this method. <ide> * Consider {@link com.nostra13.universalimageloader.utils.L#disableLogging()} to disable <ide> * ImageLoader logging completely (even error logs) <ide> return this; <ide> } <ide> <del> /** Builds configured {@link ImageLoaderConfiguration} object */ <add> /** <add> * Builds configured {@link ImageLoaderConfiguration} object <add> * ImageLoader配置项 构建 <add> */ <ide> public ImageLoaderConfiguration build() { <ide> initEmptyFieldsWithDefaultValues(); <ide> return new ImageLoaderConfiguration(this); <ide> } <ide> <add> /** <add> * 对于相关配置信息 进行默认初始化设置 <add> */ <ide> private void initEmptyFieldsWithDefaultValues() { <ide> if (taskExecutor == null) { <ide> taskExecutor = DefaultConfigurationFactory <ide> } <ide> <ide> /** <add> * 下面是对于图片下载器的装饰封装的对象--网络拒绝访问的图片下载器 <ide> * Decorator. Prevents downloads from network (throws {@link IllegalStateException exception}).<br /> <ide> * In most cases this downloader shouldn't be used directly. <ide> * <ide> } <ide> <ide> /** <add> * 下面是对于图片下载器的装饰封装的对象--网络访问速度慢的图片下载器 <ide> * Decorator. Handles <a href="http://code.google.com/p/android/issues/detail?id=6066">this problem</a> on slow networks <ide> * using {@link com.nostra13.universalimageloader.core.assist.FlushedInputStream}. <ide> *
Java
apache-2.0
57d8ac70560ad5810558057ce7cd0668ae17a696
0
customme/saiku,qixiaobo/saiku-self,qixiaobo/saiku-self,newenter/saiku,OSBI/saiku,newenter/saiku,qixiaobo/saiku-self,OSBI/saiku,OSBI/saiku,customme/saiku,customme/saiku,newenter/saiku,OSBI/saiku,customme/saiku,newenter/saiku,qixiaobo/saiku-self,OSBI/saiku
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.saiku.repository; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.saiku.database.dto.MondrianSchema; import org.saiku.datasources.connection.RepositoryFile; import org.saiku.service.user.UserService; import org.saiku.service.util.exception.SaikuServiceException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.regex.Matcher; import javax.jcr.RepositoryException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * Classpath Repository Manager for Saiku. */ public class ClassPathRepositoryManager implements IRepositoryManager { private static final Logger log = LoggerFactory.getLogger(ClassPathRepositoryManager.class); private static ClassPathRepositoryManager ref; private final String defaultRole; private UserService userService; private String append; private String session = null; private String sep = "/"; private ClassPathRepositoryManager(String config, String data, String password, String oldpassword, String defaultRole) { this.append=data; this.defaultRole = defaultRole; } /* * TODO this is currently threadsafe but to improve performance we should split it up to allow multiple sessions to hit the repo at the same time. */ public static synchronized ClassPathRepositoryManager getClassPathRepositoryManager(String config, String data, String password, String oldpassword, String defaultRole) { if (ref == null) // it's ok, we can call this constructor ref = new ClassPathRepositoryManager(config, data, password, oldpassword, defaultRole); return ref; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); // that'll teach 'em } public void init() { } public boolean start(UserService userService) throws RepositoryException { this.userService = userService; if (session == null) { log.info("starting repo"); log.info("repo started"); log.info("logging in"); log.info("logged in"); createFiles(); createFolders(); createNamespace(); createSchemas(); createDataSources(); File n = this.createFolder(sep+"homes"); HashMap<String, List<AclMethod>> m = new HashMap<>(); ArrayList<AclMethod> l = new ArrayList<>(); l.add(AclMethod.READ); m.put(defaultRole, l); AclEntry e = new AclEntry("admin", AclType.SECURED, m, null); Acl2 acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"datasources"); m = new HashMap<>(); l = new ArrayList<>(); l.add(AclMethod.WRITE); l.add(AclMethod.READ); l.add(AclMethod.GRANT); m.put("ROLE_ADMIN", l); e = new AclEntry("admin", AclType.PUBLIC, m, null); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"etc"); this.createFolder(sep+"legacyreports"); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"etc"+sep+"theme"); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); log.info("node added"); this.session = "init"; } return true; } public void createUser(String u) throws RepositoryException { File node = this.createFolder(sep+"homes"+sep+u); //node.setProperty("type", "homedirectory"); //node.setProperty("user", u); AclEntry e = new AclEntry(u, AclType.PRIVATE, null, null); Acl2 acl2 = new Acl2(node); acl2.addEntry(node.getPath(), e); acl2.serialize(node); } public Object getHomeFolders() throws RepositoryException { //login(); return this.getAllFoldersInCurrentDirectory(sep+"homes"); } public Object getHomeFolder(String path) throws RepositoryException { return this.getAllFoldersInCurrentDirectory("home:"+path); } public Object getFolder(String user, String directory) throws RepositoryException { return this.getAllFoldersInCurrentDirectory(sep+"homes"+sep+"home:"+user+sep+directory); } private Object getFolderNode(String directory) throws RepositoryException { if(directory.startsWith(sep)){ directory = directory.substring(1, directory.length()); } return this.getAllFoldersInCurrentDirectory(directory); } public void shutdown() { } public boolean createFolder(String username, String folder) throws RepositoryException { this.createFolder(folder); return true; } public boolean deleteFolder(String folder) throws RepositoryException { if(folder.startsWith(sep)){ folder = folder.substring(1, folder.length()); } /*Node n; try { n = getFolder(folder); n.remove(); } catch (RepositoryException e) { log.error("Could not remove folder: "+folder, e); }*/ this.delete(folder); return true; } public void deleteRepository() throws RepositoryException { } public boolean moveFolder(String user, String folder, String source, String target) throws RepositoryException { return false; } public Object saveFile(Object file, String path, String user, String type, List<String> roles) throws RepositoryException { if(file==null){ //Create new folder String parent; if(path.contains(sep)) { parent = path.substring(0, path.lastIndexOf(sep)); } else{ parent = sep; } File node = getFolder(parent); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if (acl2.canWrite(node, user, roles)) { throw new SaikuServiceException("Can't write to file or folder"); } int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); this.createFolder(filename); return null; } else { int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); File n = getFolder(path.substring(0, pos)); Acl2 acl2 = new Acl2(n); acl2.setAdminRoles(userService.getAdminRoles()); /*if (acl2.canWrite(n, user, roles)) { throw new SaikuServiceException("Can't write to file or folder"); }*/ File check = this.getNode(filename); if(check.exists()){ check.delete(); } File resNode = this.createNode(path); switch (type) { case "nt:saikufiles": //resNode.addMixin("nt:saikufiles"); break; case "nt:mondrianschema": //resNode.addMixin("nt:mondrianschema"); break; case "nt:olapdatasource": //resNode.addMixin("nt:olapdatasource"); break; } FileWriter fileWriter; try { fileWriter = new FileWriter(resNode); fileWriter.write((String)file); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return resNode; } } public void removeFile(String path, String user, List<String> roles) throws RepositoryException { File node = getFolder(path); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if ( !acl2.canRead(node, user, roles) ) { //TODO Throw exception throw new RepositoryException(); } this.getNode(path).delete(); } public void moveFile(String source, String target, String user, List<String> roles) throws RepositoryException { } public Object saveInternalFile(Object file, String path, String type) throws RepositoryException { if(file==null){ //Create new folder String parent = path.substring(0, path.lastIndexOf(sep)); File node = getFolder(parent); int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); this.createFolder(filename); return null; } else { int pos = path.lastIndexOf(sep); String filename = path; File check = this.getNode(filename); if(check.exists()){ check.delete(); } if(type == null){ type =""; } File f = this.createNode(filename); FileWriter fileWriter = null; try { fileWriter = new FileWriter(f); fileWriter.write((String)file); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return f; } } public Object saveBinaryInternalFile(InputStream file, String path, String type) throws RepositoryException { if(file==null){ //Create new folder String parent = path.substring(0, path.lastIndexOf(sep)); File node = getFolder(parent); int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); File resNode = this.createNode(filename); return resNode; } else { int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); // File n = getFolder(path.substring(0, pos)); if(type == null){ type =""; } log.debug("Saving:"+filename); File check = this.getNode(filename); if(check.exists()){ check.delete(); } File resNode = this.createNode(filename); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } int read = 0; byte[] bytes = new byte[1024]; try { while ((read = file.read(bytes)) != -1) { try { outputStream.write(bytes, 0, read); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } return resNode; } } public String getFile(String s, String username, List<String> roles) throws RepositoryException { File node = getFolder(s); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if ( !acl2.canRead(node, username, roles) ) { //TODO Throw exception throw new RepositoryException(); } byte[] encoded = new byte[0]; try { encoded = Files.readAllBytes(Paths.get(append+sep+s)); } catch (IOException e) { e.printStackTrace(); } try { return new String(encoded, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public String getInternalFile(String s) throws RepositoryException { byte[] encoded = new byte[0]; try { encoded = Files.readAllBytes(Paths.get(append+s)); } catch (IOException e) { e.printStackTrace(); } try { return new String(encoded, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public InputStream getBinaryInternalFile(String s) throws RepositoryException { Path path = Paths.get(s); try { byte[] f =Files.readAllBytes(path); return new ByteArrayInputStream(f); } catch (IOException e) { e.printStackTrace(); } return null; } public void removeInternalFile(String s) throws RepositoryException { this.getNode(s).delete(); } public List<MondrianSchema> getAllSchema() throws RepositoryException { /*QueryManager qm = session.getWorkspace().getQueryManager(); String sql = "SELECT * FROM [nt:mondrianschema]"; Query query = qm.createQuery(sql, Query.JCR_SQL2); QueryResult res = query.execute(); NodeIterator node = res.getNodes(); List<MondrianSchema> l = new ArrayList<>(); while (node.hasNext()) { Node n = node.nextNode(); String p = n.getPath(); MondrianSchema m = new MondrianSchema(); m.setName(n.getName()); m.setPath(p); l.add(m); } return l;*/ String[] extensions = new String[1]; extensions[0] = "xml"; Collection<File> files = FileUtils.listFiles( new File(append+"datasources"), extensions, true ); List<MondrianSchema> schema = new ArrayList<>(); for(File file: files){ try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if(line.contains("<Schema")) { MondrianSchema ms = new MondrianSchema(); ms.setName(file.getName()); ms.setPath(file.getPath()); schema.add(ms); break; } } } catch(FileNotFoundException e) { //handle this } } return schema; } public List<IRepositoryObject> getAllFiles(List<String> type, String username, List<String> roles) { try { return getRepoObjects(this.getFolder("/"), type, username, roles, false); } catch (Exception e) { e.printStackTrace(); } return null; } public List<IRepositoryObject> getAllFiles(List<String> type, String username, List<String> roles, String path) throws RepositoryException { /*Node node = this.getNodeIfExists(path, session); return getRepoObjects(node, type, username, roles, true);*/ File file = this.getNode(path); if(file.exists()) { try { return getRepoObjects(this.getFolder(path), type, username, roles, true); } catch (Exception e) { e.printStackTrace(); } } return null; } public void deleteFile(String datasourcePath) { File n; try { n = getFolder(datasourcePath); n.delete(); } catch (RepositoryException e) { log.error("Could not remove file "+datasourcePath, e ); } } private AclEntry getAclObj(String path){ File node = null; try { node = (File) getFolderNode(path); } catch (RepositoryException e) { log.error("Could not get file", e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); AclEntry entry = acl2.getEntry(path); if ( entry == null ) entry = new AclEntry(); return entry; } public AclEntry getACL(String object, String username, List<String> roles) { File node = null; try { node = (File) getFolderNode(object); } catch (RepositoryException e) { log.error("Could not get file/folder", e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if(acl2.canGrant(node, username, roles)){ return getAclObj(object); } return null; } public void setACL(String object, String acl, String username, List<String> roles) throws RepositoryException { ObjectMapper mapper = new ObjectMapper(); log.debug("Set ACL to " + object + " : " + acl); AclEntry ae = null; try { ae = mapper.readValue(acl, AclEntry.class); } catch (IOException e) { log.error("Could not read ACL blob", e); } File node = null; try { node = (File) getFolderNode(object); } catch (RepositoryException e) { log.error("Could not get file/folder "+ object, e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if (acl2.canGrant(node, username, roles)) { if (node != null) { acl2.addEntry(object, ae); acl2.serialize(node); } } } public List<MondrianSchema> getInternalFilesOfFileType(String type) throws RepositoryException { List<MondrianSchema> ds = new ArrayList<>(); String[] extensions = new String[1]; extensions[0] = "xml"; Collection<File> files = FileUtils.listFiles( new File(append), extensions, true ); for(File file: files){ String p = file.getPath(); MondrianSchema m = new MondrianSchema(); m.setName(file.getName()); m.setPath(p); m.setType(type); ds.add(m); } return ds; } public List<DataSource> getAllDataSources() throws RepositoryException { List<DataSource> ds = new ArrayList<>(); String[] extensions = new String[1]; extensions[0] = "sds"; Collection<File> files = FileUtils.listFiles( new File(append), extensions, true ); for(File file: files){ JAXBContext jaxbContext = null; Unmarshaller jaxbMarshaller = null; try { jaxbContext = JAXBContext.newInstance(DataSource.class); } catch (JAXBException e) { log.error("Could not read XML", e); } try { jaxbMarshaller = jaxbContext != null ? jaxbContext.createUnmarshaller() : null; } catch (JAXBException e) { log.error("Could not read XML", e); } InputStream stream = null; try { stream = (FileUtils.openInputStream(file)); } catch (IOException e) { e.printStackTrace(); } DataSource d = null; try { d = (DataSource) (jaxbMarshaller != null ? jaxbMarshaller.unmarshal(stream) : null); } catch (JAXBException e) { log.error("Could not read XML", e); } if (d != null) { d.setPath(file.getPath()); } ds.add(d); } return ds; } public void saveDataSource(DataSource ds, String path, String user) throws RepositoryException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { JAXBContext jaxbContext = JAXBContext.newInstance(DataSource.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ds, baos); } catch (JAXBException e) { log.error("Could not read XML", e); } int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); //File n = getFolder(path.substring(0, pos)); File f = this.createNode(path); try { FileWriter fileWriter = new FileWriter(f); fileWriter.write(baos.toString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public byte[] exportRepository() throws RepositoryException, IOException { return null; } public void restoreRepository(byte[] xml) throws RepositoryException, IOException { } public RepositoryFile getFile(String fileUrl) { File n = null; try { n = getFolder(fileUrl); } catch (RepositoryException e) { e.printStackTrace(); } return new RepositoryFile(n != null ? n.getName() : null, null, null, fileUrl); } public Object getRepository() { return null; } public void setRepository(Object repository) { //this.repository = repository; } private void createNamespace() throws RepositoryException { /*NamespaceRegistry ns = session.getWorkspace().getNamespaceRegistry(); if (!Arrays.asList(ns.getPrefixes()).contains("home")) { ns.registerNamespace("home", "http://www.meteorite.bi/namespaces/home"); }*/ } private void createDataSources() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:olapdatasource"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("enabled"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("owner"); pdt5.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } private void createSchemas() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:mondrianschema"); //ntt.setPrimaryItemName("nt:file"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("schemaname"); pdt.setRequiredType(PropertyType.STRING); pdt.isMultiple(); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("cubenames"); pdt2.setRequiredType(PropertyType.STRING); pdt2.isMultiple(); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("owner"); pdt4.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } private void createFiles() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:saikufiles"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } public void createFileMixin(String type) throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName(type); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } public Object getRepositoryObject() { return null; } private void createFolders() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:saikufolders"); String[] str = new String[]{"nt:folder"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } /* private List<IRepositoryObject> getRepoObjects(File f, List<String> fileType, String username, List<String> roles, boolean includeparent) { String[] extensions = new String[1]; Collection<File> files = FileUtils.listFiles( new File(append+f), null, true ); }*/ private List<IRepositoryObject> getRepoObjects(File root, List<String> fileType, String username, List<String> roles, boolean includeparent) throws Exception { List<IRepositoryObject> repoObjects = new ArrayList<IRepositoryObject>(); ArrayList<File> objects = new ArrayList<>(); if (root.isDirectory()) { /* objects = FileUtils.listFilesAndDirs( root, TrueFileFilter.TRUE, FalseFileFilter.FALSE );*/ this.listf(root.getAbsolutePath(), objects); } else { objects = new ArrayList<>(); objects.add(root); } Acl2 acl = new Acl2(root); acl.setAdminRoles(userService.getAdminRoles()); boolean first = false; for (File file : objects) { /*if (!first) { first = true; } else{*/ if (!file.isHidden()) { String filename = file.getName(); String relativePath = file.getPath().substring(append.length(), file.getPath().length()); if (acl.canRead(relativePath, username, roles)) { List<AclMethod> acls = acl.getMethods(relativePath, username, roles); if (file.isFile()) { if (!fileType.isEmpty()) { for (String ft : fileType) { if (!filename.endsWith(ft)) { continue; } String extension = FilenameUtils.getExtension(file.getPath()); repoObjects.add(new RepositoryFileObject(filename, "#" + relativePath, extension, relativePath, acls)); } } } if (file.isDirectory()) { repoObjects.add(new RepositoryFolderObject(filename, "#" + relativePath, relativePath, acls, getRepoObjects(file, fileType, username, roles, false))); } Collections.sort(repoObjects, new Comparator<IRepositoryObject>() { public int compare(IRepositoryObject o1, IRepositoryObject o2) { if (o1.getType().equals(IRepositoryObject.Type.FOLDER) && o2.getType().equals(IRepositoryObject.Type.FILE)) return -1; if (o1.getType().equals(IRepositoryObject.Type.FILE) && o2.getType().equals(IRepositoryObject.Type.FOLDER)) return 1; return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } }); } } } //} return repoObjects; } public void listf(String directoryName, ArrayList<File> files) { File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList) { //if (file.isFile()) { files.add(file); //} else if (file.isDirectory()) { // listf(file.getAbsolutePath(), files); // } } } private File createFolder(String path){ String appended = append+path; boolean success = (new File(appended)).mkdirs(); if (!success) { // Directory creation failed } return new File(path); } private File[] getAllFoldersInCurrentDirectory(String path){ return null; } private void delete(String folder) { File file = new File(append+folder); file.delete(); } private File getFolder(String path) throws RepositoryException { return this.getNode(path); } private File getNode(String path) { return new File(append+path); } private File createNode(String filename){ log.debug("Creating file:"+append+filename); return new File(append+filename); } }
saiku-core/saiku-service/src/main/java/org/saiku/repository/ClassPathRepositoryManager.java
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.saiku.repository; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.saiku.database.dto.MondrianSchema; import org.saiku.datasources.connection.RepositoryFile; import org.saiku.service.user.UserService; import org.saiku.service.util.exception.SaikuServiceException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.regex.Matcher; import javax.jcr.RepositoryException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * Classpath Repository Manager for Saiku. */ public class ClassPathRepositoryManager implements IRepositoryManager { private static final Logger log = LoggerFactory.getLogger(ClassPathRepositoryManager.class); private static ClassPathRepositoryManager ref; private final String defaultRole; private UserService userService; private String append; private String session = null; private String sep = File.separator; private ClassPathRepositoryManager(String config, String data, String password, String oldpassword, String defaultRole) { this.append=data; this.defaultRole = defaultRole; } /* * TODO this is currently threadsafe but to improve performance we should split it up to allow multiple sessions to hit the repo at the same time. */ public static synchronized ClassPathRepositoryManager getClassPathRepositoryManager(String config, String data, String password, String oldpassword, String defaultRole) { if (ref == null) // it's ok, we can call this constructor ref = new ClassPathRepositoryManager(config, data, password, oldpassword, defaultRole); return ref; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); // that'll teach 'em } public void init() { } public boolean start(UserService userService) throws RepositoryException { this.userService = userService; if (session == null) { log.info("starting repo"); log.info("repo started"); log.info("logging in"); log.info("logged in"); createFiles(); createFolders(); createNamespace(); createSchemas(); createDataSources(); File n = this.createFolder(sep+"homes"); HashMap<String, List<AclMethod>> m = new HashMap<>(); ArrayList<AclMethod> l = new ArrayList<>(); l.add(AclMethod.READ); m.put(defaultRole, l); AclEntry e = new AclEntry("admin", AclType.SECURED, m, null); Acl2 acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"datasources"); m = new HashMap<>(); l = new ArrayList<>(); l.add(AclMethod.WRITE); l.add(AclMethod.READ); l.add(AclMethod.GRANT); m.put("ROLE_ADMIN", l); e = new AclEntry("admin", AclType.PUBLIC, m, null); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"etc"); this.createFolder(sep+"legacyreports"); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); this.createFolder(sep+"etc"+sep+"theme"); acl2 = new Acl2(n); acl2.addEntry(n.getPath(), e); acl2.serialize(n); log.info("node added"); this.session = "init"; } return true; } public void createUser(String u) throws RepositoryException { File node = this.createFolder(sep+"homes"+sep+u); //node.setProperty("type", "homedirectory"); //node.setProperty("user", u); AclEntry e = new AclEntry(u, AclType.PRIVATE, null, null); Acl2 acl2 = new Acl2(node); acl2.addEntry(node.getPath(), e); acl2.serialize(node); } public Object getHomeFolders() throws RepositoryException { //login(); return this.getAllFoldersInCurrentDirectory(sep+"homes"); } public Object getHomeFolder(String path) throws RepositoryException { return this.getAllFoldersInCurrentDirectory("home:"+path); } public Object getFolder(String user, String directory) throws RepositoryException { return this.getAllFoldersInCurrentDirectory(sep+"homes"+sep+"home:"+user+sep+directory); } private Object getFolderNode(String directory) throws RepositoryException { if(directory.startsWith(sep)){ directory = directory.substring(1, directory.length()); } return this.getAllFoldersInCurrentDirectory(directory); } public void shutdown() { } public boolean createFolder(String username, String folder) throws RepositoryException { this.createFolder(folder); return true; } public boolean deleteFolder(String folder) throws RepositoryException { if(folder.startsWith(sep)){ folder = folder.substring(1, folder.length()); } /*Node n; try { n = getFolder(folder); n.remove(); } catch (RepositoryException e) { log.error("Could not remove folder: "+folder, e); }*/ this.delete(folder); return true; } public void deleteRepository() throws RepositoryException { } public boolean moveFolder(String user, String folder, String source, String target) throws RepositoryException { return false; } public Object saveFile(Object file, String path, String user, String type, List<String> roles) throws RepositoryException { if(file==null){ //Create new folder String parent; if(path.contains(sep)) { parent = path.substring(0, path.lastIndexOf(sep)); } else{ parent = sep; } File node = getFolder(parent); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if (acl2.canWrite(node, user, roles)) { throw new SaikuServiceException("Can't write to file or folder"); } int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); this.createFolder(filename); return null; } else { int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); File n = getFolder(path.substring(0, pos)); Acl2 acl2 = new Acl2(n); acl2.setAdminRoles(userService.getAdminRoles()); /*if (acl2.canWrite(n, user, roles)) { throw new SaikuServiceException("Can't write to file or folder"); }*/ File check = this.getNode(filename); if(check.exists()){ check.delete(); } File resNode = this.createNode(path); switch (type) { case "nt:saikufiles": //resNode.addMixin("nt:saikufiles"); break; case "nt:mondrianschema": //resNode.addMixin("nt:mondrianschema"); break; case "nt:olapdatasource": //resNode.addMixin("nt:olapdatasource"); break; } FileWriter fileWriter; try { fileWriter = new FileWriter(resNode); fileWriter.write((String)file); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return resNode; } } public void removeFile(String path, String user, List<String> roles) throws RepositoryException { File node = getFolder(path); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if ( !acl2.canRead(node, user, roles) ) { //TODO Throw exception throw new RepositoryException(); } this.getNode(path).delete(); } public void moveFile(String source, String target, String user, List<String> roles) throws RepositoryException { } public Object saveInternalFile(Object file, String path, String type) throws RepositoryException { if(file==null){ //Create new folder String parent = path.substring(0, path.lastIndexOf(sep)); File node = getFolder(parent); int pos = path.lastIndexOf(sep); String filename = "."+sep+ path.substring(pos + 1, path.length()); this.createFolder(filename); return null; } else { int pos = path.lastIndexOf(sep); String filename = path; File check = this.getNode(filename); if(check.exists()){ check.delete(); } if(type == null){ type =""; } File f = this.createNode(filename); FileWriter fileWriter = null; try { fileWriter = new FileWriter(f); fileWriter.write((String)file); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } return f; } } public Object saveBinaryInternalFile(InputStream file, String path, String type) throws RepositoryException { if(file==null){ //Create new folder String parent = path.substring(0, path.lastIndexOf(sep)); File node = getFolder(parent); int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); File resNode = this.createNode(filename); return resNode; } else { int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); // File n = getFolder(path.substring(0, pos)); if(type == null){ type =""; } log.debug("Saving:"+filename); File check = this.getNode(filename); if(check.exists()){ check.delete(); } File resNode = this.createNode(filename); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } int read = 0; byte[] bytes = new byte[1024]; try { while ((read = file.read(bytes)) != -1) { try { outputStream.write(bytes, 0, read); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } return resNode; } } public String getFile(String s, String username, List<String> roles) throws RepositoryException { File node = getFolder(s); Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if ( !acl2.canRead(node, username, roles) ) { //TODO Throw exception throw new RepositoryException(); } byte[] encoded = new byte[0]; try { encoded = Files.readAllBytes(Paths.get(append+sep+s)); } catch (IOException e) { e.printStackTrace(); } try { return new String(encoded, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public String getInternalFile(String s) throws RepositoryException { byte[] encoded = new byte[0]; try { encoded = Files.readAllBytes(Paths.get(append+s)); } catch (IOException e) { e.printStackTrace(); } try { return new String(encoded, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public InputStream getBinaryInternalFile(String s) throws RepositoryException { Path path = Paths.get(s); try { byte[] f =Files.readAllBytes(path); return new ByteArrayInputStream(f); } catch (IOException e) { e.printStackTrace(); } return null; } public void removeInternalFile(String s) throws RepositoryException { this.getNode(s).delete(); } public List<MondrianSchema> getAllSchema() throws RepositoryException { /*QueryManager qm = session.getWorkspace().getQueryManager(); String sql = "SELECT * FROM [nt:mondrianschema]"; Query query = qm.createQuery(sql, Query.JCR_SQL2); QueryResult res = query.execute(); NodeIterator node = res.getNodes(); List<MondrianSchema> l = new ArrayList<>(); while (node.hasNext()) { Node n = node.nextNode(); String p = n.getPath(); MondrianSchema m = new MondrianSchema(); m.setName(n.getName()); m.setPath(p); l.add(m); } return l;*/ String[] extensions = new String[1]; extensions[0] = "xml"; Collection<File> files = FileUtils.listFiles( new File(append+"datasources"), extensions, true ); List<MondrianSchema> schema = new ArrayList<>(); for(File file: files){ try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if(line.contains("<Schema")) { MondrianSchema ms = new MondrianSchema(); ms.setName(file.getName()); ms.setPath(file.getPath()); schema.add(ms); break; } } } catch(FileNotFoundException e) { //handle this } } return schema; } public List<IRepositoryObject> getAllFiles(List<String> type, String username, List<String> roles) { try { return getRepoObjects(this.getFolder("/"), type, username, roles, false); } catch (Exception e) { e.printStackTrace(); } return null; } public List<IRepositoryObject> getAllFiles(List<String> type, String username, List<String> roles, String path) throws RepositoryException { /*Node node = this.getNodeIfExists(path, session); return getRepoObjects(node, type, username, roles, true);*/ File file = this.getNode(path); if(file.exists()) { try { return getRepoObjects(this.getFolder(path), type, username, roles, true); } catch (Exception e) { e.printStackTrace(); } } return null; } public void deleteFile(String datasourcePath) { File n; try { n = getFolder(datasourcePath); n.delete(); } catch (RepositoryException e) { log.error("Could not remove file "+datasourcePath, e ); } } private AclEntry getAclObj(String path){ File node = null; try { node = (File) getFolderNode(path); } catch (RepositoryException e) { log.error("Could not get file", e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); AclEntry entry = acl2.getEntry(path); if ( entry == null ) entry = new AclEntry(); return entry; } public AclEntry getACL(String object, String username, List<String> roles) { File node = null; try { node = (File) getFolderNode(object); } catch (RepositoryException e) { log.error("Could not get file/folder", e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if(acl2.canGrant(node, username, roles)){ return getAclObj(object); } return null; } public void setACL(String object, String acl, String username, List<String> roles) throws RepositoryException { ObjectMapper mapper = new ObjectMapper(); log.debug("Set ACL to " + object + " : " + acl); AclEntry ae = null; try { ae = mapper.readValue(acl, AclEntry.class); } catch (IOException e) { log.error("Could not read ACL blob", e); } File node = null; try { node = (File) getFolderNode(object); } catch (RepositoryException e) { log.error("Could not get file/folder "+ object, e); } Acl2 acl2 = new Acl2(node); acl2.setAdminRoles(userService.getAdminRoles()); if (acl2.canGrant(node, username, roles)) { if (node != null) { acl2.addEntry(object, ae); acl2.serialize(node); } } } public List<MondrianSchema> getInternalFilesOfFileType(String type) throws RepositoryException { List<MondrianSchema> ds = new ArrayList<>(); String[] extensions = new String[1]; extensions[0] = "xml"; Collection<File> files = FileUtils.listFiles( new File(append), extensions, true ); for(File file: files){ String p = file.getPath(); MondrianSchema m = new MondrianSchema(); m.setName(file.getName()); m.setPath(p); m.setType(type); ds.add(m); } return ds; } public List<DataSource> getAllDataSources() throws RepositoryException { List<DataSource> ds = new ArrayList<>(); String[] extensions = new String[1]; extensions[0] = "sds"; Collection<File> files = FileUtils.listFiles( new File(append), extensions, true ); for(File file: files){ JAXBContext jaxbContext = null; Unmarshaller jaxbMarshaller = null; try { jaxbContext = JAXBContext.newInstance(DataSource.class); } catch (JAXBException e) { log.error("Could not read XML", e); } try { jaxbMarshaller = jaxbContext != null ? jaxbContext.createUnmarshaller() : null; } catch (JAXBException e) { log.error("Could not read XML", e); } InputStream stream = null; try { stream = (FileUtils.openInputStream(file)); } catch (IOException e) { e.printStackTrace(); } DataSource d = null; try { d = (DataSource) (jaxbMarshaller != null ? jaxbMarshaller.unmarshal(stream) : null); } catch (JAXBException e) { log.error("Could not read XML", e); } if (d != null) { d.setPath(file.getPath()); } ds.add(d); } return ds; } public void saveDataSource(DataSource ds, String path, String user) throws RepositoryException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { JAXBContext jaxbContext = JAXBContext.newInstance(DataSource.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ds, baos); } catch (JAXBException e) { log.error("Could not read XML", e); } int pos = path.lastIndexOf(sep); String filename = "."+sep + path.substring(pos + 1, path.length()); //File n = getFolder(path.substring(0, pos)); File f = this.createNode(path); try { FileWriter fileWriter = new FileWriter(f); fileWriter.write(baos.toString()); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public byte[] exportRepository() throws RepositoryException, IOException { return null; } public void restoreRepository(byte[] xml) throws RepositoryException, IOException { } public RepositoryFile getFile(String fileUrl) { File n = null; try { n = getFolder(fileUrl); } catch (RepositoryException e) { e.printStackTrace(); } return new RepositoryFile(n != null ? n.getName() : null, null, null, fileUrl); } public Object getRepository() { return null; } public void setRepository(Object repository) { //this.repository = repository; } private void createNamespace() throws RepositoryException { /*NamespaceRegistry ns = session.getWorkspace().getNamespaceRegistry(); if (!Arrays.asList(ns.getPrefixes()).contains("home")) { ns.registerNamespace("home", "http://www.meteorite.bi/namespaces/home"); }*/ } private void createDataSources() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:olapdatasource"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("enabled"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("owner"); pdt5.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } private void createSchemas() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:mondrianschema"); //ntt.setPrimaryItemName("nt:file"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("schemaname"); pdt.setRequiredType(PropertyType.STRING); pdt.isMultiple(); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("cubenames"); pdt2.setRequiredType(PropertyType.STRING); pdt2.isMultiple(); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("owner"); pdt4.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } private void createFiles() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:saikufiles"); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } public void createFileMixin(String type) throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName(type); String[] str = new String[]{"nt:file"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt3 = manager.createPropertyDefinitionTemplate(); pdt3.setName("jcr:data"); pdt3.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt3); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } public Object getRepositoryObject() { return null; } private void createFolders() throws RepositoryException { /* NodeTypeManager manager = session.getWorkspace().getNodeTypeManager(); NodeTypeTemplate ntt = manager.createNodeTypeTemplate(); ntt.setName("nt:saikufolders"); String[] str = new String[]{"nt:folder"}; ntt.setDeclaredSuperTypeNames(str); ntt.setMixin(true); PropertyDefinitionTemplate pdt = manager.createPropertyDefinitionTemplate(); pdt.setName("owner"); pdt.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt2 = manager.createPropertyDefinitionTemplate(); pdt2.setName("type"); pdt2.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt4 = manager.createPropertyDefinitionTemplate(); pdt4.setName("roles"); pdt4.setRequiredType(PropertyType.STRING); PropertyDefinitionTemplate pdt5 = manager.createPropertyDefinitionTemplate(); pdt5.setName("users"); pdt5.setRequiredType(PropertyType.STRING); ntt.getPropertyDefinitionTemplates().add(pdt); ntt.getPropertyDefinitionTemplates().add(pdt2); ntt.getPropertyDefinitionTemplates().add(pdt4); ntt.getPropertyDefinitionTemplates().add(pdt5); try { manager.registerNodeType(ntt, false); } catch(NodeTypeExistsException ignored){ }*/ } /* private List<IRepositoryObject> getRepoObjects(File f, List<String> fileType, String username, List<String> roles, boolean includeparent) { String[] extensions = new String[1]; Collection<File> files = FileUtils.listFiles( new File(append+f), null, true ); }*/ private List<IRepositoryObject> getRepoObjects(File root, List<String> fileType, String username, List<String> roles, boolean includeparent) throws Exception { List<IRepositoryObject> repoObjects = new ArrayList<IRepositoryObject>(); ArrayList<File> objects = new ArrayList<>(); if (root.isDirectory()) { /* objects = FileUtils.listFilesAndDirs( root, TrueFileFilter.TRUE, FalseFileFilter.FALSE );*/ this.listf(root.getAbsolutePath(), objects); } else { objects = new ArrayList<>(); objects.add(root); } Acl2 acl = new Acl2(root); acl.setAdminRoles(userService.getAdminRoles()); boolean first = false; for (File file : objects) { /*if (!first) { first = true; } else{*/ if (!file.isHidden()) { String filename = file.getName(); String relativePath = file.getPath().substring(append.length(), file.getPath().length()); if (acl.canRead(relativePath, username, roles)) { List<AclMethod> acls = acl.getMethods(relativePath, username, roles); if (file.isFile()) { if (!fileType.isEmpty()) { for (String ft : fileType) { if (!filename.endsWith(ft)) { continue; } String extension = FilenameUtils.getExtension(file.getPath()); repoObjects.add(new RepositoryFileObject(filename, "#" + relativePath, extension, relativePath, acls)); } } } if (file.isDirectory()) { repoObjects.add(new RepositoryFolderObject(filename, "#" + relativePath, relativePath, acls, getRepoObjects(file, fileType, username, roles, false))); } Collections.sort(repoObjects, new Comparator<IRepositoryObject>() { public int compare(IRepositoryObject o1, IRepositoryObject o2) { if (o1.getType().equals(IRepositoryObject.Type.FOLDER) && o2.getType().equals(IRepositoryObject.Type.FILE)) return -1; if (o1.getType().equals(IRepositoryObject.Type.FILE) && o2.getType().equals(IRepositoryObject.Type.FOLDER)) return 1; return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } }); } } } //} return repoObjects; } public void listf(String directoryName, ArrayList<File> files) { File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList) { //if (file.isFile()) { files.add(file); //} else if (file.isDirectory()) { // listf(file.getAbsolutePath(), files); // } } } private File createFolder(String path){ String appended = append+path; boolean success = (new File(appended)).mkdirs(); if (!success) { // Directory creation failed } return new File(path); } private File[] getAllFoldersInCurrentDirectory(String path){ return null; } private void delete(String folder) { File file = new File(append+folder); file.delete(); } private File getFolder(String path) throws RepositoryException { return this.getNode(path); } private File getNode(String path) { return new File(append+path); } private File createNode(String filename){ log.debug("Creating file:"+append+filename); return new File(append+filename); } }
remove unneeded lookup
saiku-core/saiku-service/src/main/java/org/saiku/repository/ClassPathRepositoryManager.java
remove unneeded lookup
<ide><path>aiku-core/saiku-service/src/main/java/org/saiku/repository/ClassPathRepositoryManager.java <ide> private String append; <ide> private String session = null; <ide> <del> private String sep = File.separator; <add> private String sep = "/"; <ide> private ClassPathRepositoryManager(String config, String data, String password, String oldpassword, String defaultRole) { <ide> <ide> this.append=data;
JavaScript
mit
b2db7a72088aa77217b356b4e13f4788bcbc2a69
0
jeffeb3/sandify,jeffeb3/sandify,jeffeb3/sandify
import React, { Component } from 'react'; import { Col, ControlLabel, Form, FormControl, FormGroup, ListGroup, ListGroupItem, Panel, } from 'react-bootstrap' import './Transforms.css' import Vicious1Vertices from './Vicious1Vertices'; import { Font2 } from './Fonts'; import { Vertex } from '../Geometry'; import { connect } from 'react-redux' // Transform actions export const addShape = ( shape ) => { return { type: 'ADD_SHAPE', shape: shape, }; } export const setShape = ( shape ) => { return { type: 'SET_SHAPE', value: shape, }; } export const setShapePolygonSides = ( sides ) => { return { type: 'SET_SHAPE_POLYGON_SIDES', value: sides, }; } export const setShapeStarPoints = ( sides ) => { return { type: 'SET_SHAPE_STAR_POINTS', value: sides, }; } export const setShapeStarRatio = ( value ) => { return { type: 'SET_SHAPE_STAR_RATIO', value: Math.min(Math.max(value, 0.0), 1.0), }; } export const setShapeCircleLobes = ( sides ) => { return { type: 'SET_SHAPE_CIRCLE_LOBES', value: sides, }; } export const setShapeReuleauxSides = ( sides ) => { return { type: 'SET_SHAPE_REULEAUX_SIDES', value: sides, }; } export const setShapeepicycloidA = ( a ) => { return { type: 'SET_SHAPE_EPICYCLOID_A', value: a, }; } export const setShapeepicycloidB = ( b ) => { return { type: 'SET_SHAPE_EPICYCLOID_B', value: b, }; } export const setShapehypocycloidA = ( a ) => { return { type: 'SET_SHAPE_HYPOCYCLOID_A', value: a, }; } export const setShapehypocycloidB = ( b ) => { return { type: 'SET_SHAPE_HYPOCYCLOID_B', value: b, }; } export const setShapeRoseN = ( n ) => { return { type: 'SET_SHAPE_ROSE_N', value: n, }; } export const setShapeRoseD = ( d ) => { return { type: 'SET_SHAPE_ROSE_D', value: d, }; } export const setShapeInputText = ( text ) => { return { type: 'SET_SHAPE_INPUT_TEXT', value: text, }; } export const setShapeSize = ( size ) => { return { type: 'SET_SHAPE_SIZE', value: size, }; } export const setXFormOffsetX = ( offset ) => { return { type: 'SET_SHAPE_OFFSET_X', value: parseFloat(offset), }; } export const setXFormOffsetY = ( offset ) => { return { type: 'SET_SHAPE_OFFSET_Y', value: parseFloat(offset), }; } export const setLoops = ( loops ) => { return { type: 'SET_LOOPS', value: loops, }; } export const toggleSpin = ( ) => { return { type: 'TOGGLE_SPIN', }; } export const setSpin = ( value ) => { return { type: 'SET_SPIN', value: parseFloat(value), }; } export const setSpinSwitchbacks = ( value ) => { return { type: 'SET_SPIN_SWITCHBACKS', value: parseInt(value), }; } export const toggleGrow = ( ) => { return { type: 'TOGGLE_GROW', }; } export const setGrow = ( value ) => { return { type: 'SET_GROW', value: value, }; } export const toggleTrack = ( ) => { return { type: 'TOGGLE_TRACK', }; } export const toggleTrackGrow = ( ) => { return { type: 'TOGGLE_TRACK_GROW', }; } export const setTrack = ( value ) => { return { type: 'SET_TRACK', value: value, }; } export const setTrackLength = ( value ) => { return { type: 'SET_TRACK_LENGTH', value: value, }; } export const setTrackGrow = ( value ) => { return { type: 'SET_TRACK_GROW', value: value, }; } const disableEnter = (event) => { if (event.key === 'Enter' && event.shiftKey === false) { event.preventDefault(); } }; class Shape extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } var options_render = this.props.options.map( (option) => { return <FormGroup controlId="options-step" key={option.title}> <Col componentClass={ControlLabel} sm={4}> {option.title} </Col> <Col sm={8}> <FormControl type={option.type ? option.type : "number"} step={option.step ? option.step : 1} value={option.value()} onChange={(event) => { option.onChange(event) }} onKeyDown={disableEnter}/> </Col> </FormGroup> }); var options_list_render = undefined; var link_render = undefined; if (this.props.link) { link_render = <p>See <a target="_blank" rel="noopener noreferrer" href={this.props.link}>{this.props.link}</a> for ideas</p>; } if (this.props.options.length >= 1) { options_list_render = <div className="shape-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> {link_render} {options_render} </Form> </Panel> </div> } return ( <div className="shape"> <ListGroupItem className={activeClassName} onClick={this.props.clicked}>{this.props.name}</ListGroupItem> {options_list_render} </div> ) } } const shapeListProps = (state, ownProps) => { return { shapes: state.shapes.shapes, polygonSides: state.shapes.polygonSides, starPoints: state.shapes.starPoints, starRatio: state.shapes.starRatio, circleLobes: state.shapes.circleLobes, reuleauxSides: state.shapes.reuleauxSides, epicycloidA: state.shapes.epicycloidA, epicycloidB: state.shapes.epicycloidB, hypocycloidA: state.shapes.hypocycloidA, hypocycloidB: state.shapes.hypocycloidB, roseN: state.shapes.roseN, roseD: state.shapes.roseD, inputText: state.shapes.inputText, currentShape: state.shapes.currentShape, startingSize: state.shapes.startingSize, x_offset: state.transform.xformOffsetX, y_offset: state.transform.xformOffsetY, } } const shapeListDispatch = (dispatch, ownProps) => { return { addShape: (shape) => { dispatch(addShape(shape)); }, setShape: (name) => { dispatch(setShape(name)); }, onPolygonSizeChange: (event) => { dispatch(setShapePolygonSides(event.target.value)); }, onStarPointsChange: (event) => { dispatch(setShapeStarPoints(event.target.value)); }, onStarRatioChange: (event) => { dispatch(setShapeStarRatio(event.target.value)); }, onCircleLobesChange: (event) => { dispatch(setShapeCircleLobes(event.target.value)); }, onReuleauxSidesChange: (event) => { dispatch(setShapeReuleauxSides(event.target.value)); }, onepicycloidAChange: (event) => { dispatch(setShapeepicycloidA(event.target.value)); }, onepicycloidBChange: (event) => { dispatch(setShapeepicycloidB(event.target.value)); }, onhypocycloidAChange: (event) => { dispatch(setShapehypocycloidA(event.target.value)); }, onhypocycloidBChange: (event) => { dispatch(setShapehypocycloidB(event.target.value)); }, onRoseNChange: (event) => { dispatch(setShapeRoseN(event.target.value)); }, onRoseDChange: (event) => { dispatch(setShapeRoseD(event.target.value)); }, onInputTextChange: (event) => { dispatch(setShapeInputText(event.target.value)); }, onSizeChange: (event) => { dispatch(setShapeSize(event.target.value)); }, onOffsetXChange: (event) => { dispatch(setXFormOffsetX(event.target.value)); }, onOffsetYChange: (event) => { dispatch(setXFormOffsetY(event.target.value)); }, } } class ShapeList extends Component { constructor(props) { super(props) this.props.addShape({ name: "Polygon", vertices: (state) => { let points = []; for (let i=0; i<state.shapes.polygonSides; i++) { let angle = Math.PI * 2.0 / state.shapes.polygonSides * (0.5 + i); points.push(Vertex(Math.cos(angle), Math.sin(angle))) } return points; }, options: [ { title: "Number of Sides", value: () => { return this.props.polygonSides }, onChange: this.props.onPolygonSizeChange, }, ], }); this.props.addShape({ name: "Star", vertices: (state) => { let star_points = []; for (let i=0; i<state.shapes.starPoints * 2; i++) { let angle = Math.PI * 2.0 / (2.0 * state.shapes.starPoints) * i; let star_scale = 1.0; if (i % 2 === 0) { star_scale *= state.shapes.starRatio; } star_points.push(Vertex(star_scale * Math.cos(angle), star_scale * Math.sin(angle))) } return star_points }, options: [ { title: "Number of Points", value: () => { return this.props.starPoints }, onChange: this.props.onStarPointsChange, }, { title: "Size of Points", value: () => { return this.props.starRatio }, onChange: this.props.onStarRatioChange, step: 0.05, }, ], }); this.props.addShape({ name: "Circle", vertices: (state) => { let circle_points = [] for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i circle_points.push(Vertex(Math.cos(angle), Math.sin(state.shapes.circleLobes * angle)/state.shapes.circleLobes)) } return circle_points }, options: [ { title: "Number of Lobes", value: () => { return this.props.circleLobes }, onChange: this.props.onCircleLobesChange, }, ], }); this.props.addShape({ name: "Heart", vertices: (state) => { let heart_points = [] for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i // heart equation from: http://mathworld.wolfram.com/HeartCurve.html heart_points.push(Vertex(1.0 * Math.pow(Math.sin(angle), 3), 13.0/16.0 * Math.cos(angle) + -5.0/16.0 * Math.cos(2.0 * angle) + -2.0/16.0 * Math.cos(3.0 * angle) + -1.0/16.0 * Math.cos(4.0 * angle))) } return heart_points }, options: [ ], }); this.props.addShape({ name: "Reuleaux", vertices: (state) => { let points = [] // Construct an equalateral triangle let corners = [] // Initial location at PI/2 let angle = Math.PI/2.0; // How much of the circle in one side? let coverageAngle = Math.PI/state.shapes.reuleauxSides; let halfCoverageAngle = 0.5 * coverageAngle; for (let c=0; c<state.shapes.reuleauxSides; c++) { let startAngle = angle + Math.PI - halfCoverageAngle; corners.push( [Vertex(Math.cos(angle), Math.sin(angle)), startAngle] ); angle += 2.0 * Math.PI / state.shapes.reuleauxSides; } let length = 0.5 / Math.cos(Math.PI/2.0/state.shapes.reuleauxSides); for (let corn=0; corn < corners.length; corn++) { for (let i=0; i<128; i++) { let angle = coverageAngle * (i / 128.0) + corners[corn][1]; points.push(Vertex(length * corners[corn][0].x + Math.cos(angle), length * corners[corn][0].y + Math.sin(angle))); } } return points; }, options: [ { title: "Number of sides", value: () => { return this.props.reuleauxSides }, onChange: this.props.onReuleauxSidesChange, step: 1, }, ], }); this.props.addShape( { name: "Clover", link: "http://mathworld.wolfram.com/Epicycloid.html", vertices: (state) => { let points = [] let a = parseFloat(state.shapes.epicycloidA) let b = parseFloat(state.shapes.epicycloidB) for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i points.push(Vertex(0.5 * (a + b) * Math.cos(angle) - 0.5 * b * Math.cos(((a + b) / b) * angle), 0.5 * (a + b) * Math.sin(angle) - 0.5 * b * Math.sin(((a + b) / b) * angle))) } return points }, options: [ { title: "Large circle radius", value: () => { return this.props.epicycloidA }, onChange: this.props.onepicycloidAChange, step: 0.1, }, { title: "Small circle radius", value: () => { return this.props.epicycloidB }, onChange: this.props.onepicycloidBChange, step: 0.1, }, ], }); this.props.addShape( { name: "Web", link: "http://mathworld.wolfram.com/Hypocycloid.html", vertices: (state) => { let points = [] let a = parseFloat(state.shapes.hypocycloidA) let b = parseFloat(state.shapes.hypocycloidB) for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i points.push(Vertex(1.0 * (a - b) * Math.cos(angle) + b * Math.cos(((a - b) / b) * angle), 1.0 * (a - b) * Math.sin(angle) - b * Math.sin(((a - b) / b) * angle))) } return points }, options: [ { title: "Large circle radius", value: () => { return this.props.hypocycloidA }, onChange: this.props.onhypocycloidAChange, step: 0.1, }, { title: "Small circle radius", value: () => { return this.props.hypocycloidB }, onChange: this.props.onhypocycloidBChange, step: 0.1, }, ], }); this.props.addShape({ name: "Rose", link: "http://mathworld.wolfram.com/Rose.html", vertices: (state) => { let points = [] let a = 2 let n = parseInt(state.shapes.roseN) let d = parseInt(state.shapes.roseD) let p = (n * d % 2 === 0) ? 2 : 1 let thetaClose = d * p * 32 * n; let resolution = 64 * n; for (let i=0; i<thetaClose+1; i++) { let theta = Math.PI * 2.0 / (resolution) * i let r = 0.5 * a * Math.sin((n / d) * theta) points.push(Vertex(r * Math.cos(theta), r * Math.sin(theta))) } return points }, options: [ { title: "Numerator", value: () => { return this.props.roseN }, onChange: this.props.onRoseNChange, step: 1, }, { title: "Denominator", value: () => { return this.props.roseD }, onChange: this.props.onRoseDChange, step: 1, }, ], }); this.props.addShape({ name: "Text", vertices: (state) => { let points = []; const under_y = -0.25; points.push(Vertex(0.0, under_y)) let x = 0.0; for (let chi = 0; chi < state.shapes.inputText.length; chi++) { var letter = Font2(state.shapes.inputText[chi]); if (0 < letter.vertices.length) { points.push(Vertex(x + letter.vertices[0].x, under_y)) } for (let vi = 0; vi < letter.vertices.length; vi++) { points.push(Vertex(letter.vertices[vi].x + x, letter.vertices[vi].y)); } if (0 < letter.vertices.length) { points.push(Vertex(x + letter.vertices[letter.vertices.length-1].x, under_y)) } if (chi !== state.shapes.inputText.length-1) { points.push(Vertex(x + letter.max_x, under_y)) } x += letter.max_x; } let widthOffset = x / 2.0; return points.map( (point) => { return Vertex(point.x - widthOffset, point.y); }); }, options: [ { title: "Text", type: "textarea", value: () => { return this.props.inputText }, onChange: this.props.onInputTextChange, }, ], }); this.props.addShape({ name: "V1Engineering", vertices: (state) => { return Vicious1Vertices() }, options: [], }); } render() { let self = this; var shape_render = this.props.shapes.map( (shape) => { return <Shape key={shape.name} name={shape.name} link={shape.link || ""} active={shape.name === self.props.currentShape} options={shape.options} clicked={ () => { self.props.setShape(shape.name); } } /> }); return ( <div className="shapes"> <ListGroup> {shape_render} </ListGroup> <div className="shoptions"> <Panel className="options-panel" collapsible expanded> <Form horizontal> <FormGroup controlId="shape-size"> <Col componentClass={ControlLabel} sm={4}> Starting Size </Col> <Col sm={8}> <FormControl type="number" value={this.props.startingSize} onChange={this.props.onSizeChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="shape-offset"> <Col componentClass={ControlLabel} sm={4}> Offset </Col> <Col componentClass={ControlLabel} sm={1}> X </Col> <Col sm={3}> <FormControl type="number" value={this.props.x_offset} onChange={this.props.onOffsetXChange} onKeyDown={disableEnter}/> </Col> <Col componentClass={ControlLabel} sm={1}> Y </Col> <Col sm={3}> <FormControl type="number" value={this.props.y_offset} onChange={this.props.onOffsetYChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } ShapeList = connect(shapeListProps, shapeListDispatch)(ShapeList) ; const rotateProps = (state, ownProps) => { return { active: state.transform.spinEnabled, value: state.transform.spinValue, switchbacks: state.transform.spinSwitchbacks, } } const rotateDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleSpin()); }, onChange: (event) => { dispatch(setSpin(event.target.value)); }, onSwitchbacksChange: (event) => { dispatch(setSpinSwitchbacks(event.target.value)); }, } } class RotationTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } return ( <div className="rotate"> <ListGroupItem header="Spin" className={activeClassName} onClick={this.props.activeCallback}>Spins the input shape a little bit for each copy</ListGroupItem> <div className="rotate-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="rotate-step"> <Col componentClass={ControlLabel} sm={4}> Spin Step (Can be Negative) </Col> <Col sm={8}> <FormControl type="number" step="0.1" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="rotate-switchbacks"> <Col componentClass={ControlLabel} sm={4}> Switchbacks </Col> <Col sm={8}> <FormControl type="number" step="1" value={this.props.switchbacks} onChange={this.props.onSwitchbacksChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } RotationTransform = connect(rotateProps, rotateDispatch)(RotationTransform) ; const scaleProps = (state, ownProps) => { return { active: state.transform.growEnabled, value: state.transform.growValue, } } const scaleDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleGrow()); }, onChange: (event) => { dispatch(setGrow(event.target.value)); }, } } class ScaleTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } return ( <div className="scale"> <ListGroupItem header="Grow" className={activeClassName} onClick={this.props.activeCallback}>Grows or shrinks the input shape a little bit for each copy</ListGroupItem> <div className="scale-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="scale-step"> <Col componentClass={ControlLabel} sm={4}> Grow Step </Col> <Col sm={8}> <FormControl type="number" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } ScaleTransform = connect(scaleProps, scaleDispatch)(ScaleTransform) ; const trackProps = (state, ownProps) => { return { active: state.transform.trackEnabled, activeGrow: state.transform.trackGrowEnabled, value: state.transform.trackValue, length: state.transform.trackLength, trackGrow: state.transform.trackGrow, } } const trackDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleTrack()); }, activeGrowCallback: () => { dispatch(toggleTrackGrow()); }, onChange: (event) => { dispatch(setTrack(event.target.value)); }, onChangeLength: (event) => { dispatch(setTrackLength(event.target.value)); }, onChangeGrow: (event) => { dispatch(setTrackGrow(event.target.value)); }, } } class TrackTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } var activeGrowClassName = ""; if (this.props.activeGrow) { activeGrowClassName = "active"; } return ( <div className="track"> <ListGroupItem header="Track" className={activeClassName} onClick={this.props.activeCallback}>Moves the shape along a track (shown in green)</ListGroupItem> <div className="track-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="track-size"> <Col componentClass={ControlLabel} sm={4}> Track Size </Col> <Col sm={8}> <FormControl type="number" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="track-length"> <Col componentClass={ControlLabel} sm={4}> Track Length </Col> <Col sm={8}> <FormControl type="number" value={this.props.length} step="0.05" onChange={this.props.onChangeLength} onKeyDown={disableEnter}/> </Col> </FormGroup> <ListGroupItem header="Grow" className={activeGrowClassName} onClick={this.props.activeGrowCallback}>Grows or shrinks the track a little bit for each step</ListGroupItem> <div className="scale-options"> <Panel className="options-panel" collapsible expanded={this.props.activeGrow}> <FormGroup controlId="scale-step"> <Col componentClass={ControlLabel} sm={4}> Track Grow Step </Col> <Col sm={8}> <FormControl type="number" value={this.props.trackGrow} onChange={this.props.onChangeGrow} onKeyDown={disableEnter}/> </Col> </FormGroup> </Panel> </div> </Form> </Panel> </div> </div> ) } } TrackTransform = connect(trackProps, trackDispatch)(TrackTransform) ; const transformsProps = (state, ownProps) => { return { loops: state.transform.numLoops, } } const transformsDispatch = (dispatch, ownProps) => { return { changeLoops: (event) => { dispatch(setLoops(event.target.value)); }, } } class Transforms extends Component { render() { return ( <div className="transforms"> <Panel className="shapes-panel"> <h4>Input Shapes</h4> <ShapeList /> </Panel> <Panel className="transforms-panel"> <h4>Modifiers</h4> <Panel className="options-panel"> <Form horizontal> <FormGroup controlId="loop-count"> <Col componentClass={ControlLabel} sm={4}> Number of Loops </Col> <Col sm={8}> <FormControl type="number" value={this.props.loops} onChange={this.props.changeLoops} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> <ListGroup> <ScaleTransform /> <RotationTransform /> <TrackTransform /> </ListGroup> </Panel> </div> ); } } Transforms = connect(transformsProps, transformsDispatch)(Transforms); export default Transforms
src/inputs/Transforms.js
import React, { Component } from 'react'; import { Col, ControlLabel, Form, FormControl, FormGroup, ListGroup, ListGroupItem, Panel, } from 'react-bootstrap' import './Transforms.css' import Vicious1Vertices from './Vicious1Vertices'; import { Font2 } from './Fonts'; import { Vertex } from '../Geometry'; import { connect } from 'react-redux' // Transform actions export const addShape = ( shape ) => { return { type: 'ADD_SHAPE', shape: shape, }; } export const setShape = ( shape ) => { return { type: 'SET_SHAPE', value: shape, }; } export const setShapePolygonSides = ( sides ) => { return { type: 'SET_SHAPE_POLYGON_SIDES', value: sides, }; } export const setShapeStarPoints = ( sides ) => { return { type: 'SET_SHAPE_STAR_POINTS', value: sides, }; } export const setShapeStarRatio = ( value ) => { return { type: 'SET_SHAPE_STAR_RATIO', value: Math.min(Math.max(value, 0.0), 1.0), }; } export const setShapeCircleLobes = ( sides ) => { return { type: 'SET_SHAPE_CIRCLE_LOBES', value: sides, }; } export const setShapeReuleauxSides = ( sides ) => { return { type: 'SET_SHAPE_REULEAUX_SIDES', value: sides, }; } export const setShapeepicycloidA = ( a ) => { return { type: 'SET_SHAPE_EPICYCLOID_A', value: a, }; } export const setShapeepicycloidB = ( b ) => { return { type: 'SET_SHAPE_EPICYCLOID_B', value: b, }; } export const setShapehypocycloidA = ( a ) => { return { type: 'SET_SHAPE_HYPOCYCLOID_A', value: a, }; } export const setShapehypocycloidB = ( b ) => { return { type: 'SET_SHAPE_HYPOCYCLOID_B', value: b, }; } export const setShapeRoseN = ( n ) => { return { type: 'SET_SHAPE_ROSE_N', value: n, }; } export const setShapeRoseD = ( d ) => { return { type: 'SET_SHAPE_ROSE_D', value: d, }; } export const setShapeInputText = ( text ) => { return { type: 'SET_SHAPE_INPUT_TEXT', value: text, }; } export const setShapeSize = ( size ) => { return { type: 'SET_SHAPE_SIZE', value: size, }; } export const setXFormOffsetX = ( offset ) => { return { type: 'SET_SHAPE_OFFSET_X', value: parseFloat(offset), }; } export const setXFormOffsetY = ( offset ) => { return { type: 'SET_SHAPE_OFFSET_Y', value: parseFloat(offset), }; } export const setLoops = ( loops ) => { return { type: 'SET_LOOPS', value: loops, }; } export const toggleSpin = ( ) => { return { type: 'TOGGLE_SPIN', }; } export const setSpin = ( value ) => { return { type: 'SET_SPIN', value: parseFloat(value), }; } export const setSpinSwitchbacks = ( value ) => { return { type: 'SET_SPIN_SWITCHBACKS', value: parseInt(value), }; } export const toggleGrow = ( ) => { return { type: 'TOGGLE_GROW', }; } export const setGrow = ( value ) => { return { type: 'SET_GROW', value: value, }; } export const toggleTrack = ( ) => { return { type: 'TOGGLE_TRACK', }; } export const toggleTrackGrow = ( ) => { return { type: 'TOGGLE_TRACK_GROW', }; } export const setTrack = ( value ) => { return { type: 'SET_TRACK', value: value, }; } export const setTrackLength = ( value ) => { return { type: 'SET_TRACK_LENGTH', value: value, }; } export const setTrackGrow = ( value ) => { return { type: 'SET_TRACK_GROW', value: value, }; } const disableEnter = (event) => { if (event.key === 'Enter' && event.shiftKey === false) { event.preventDefault(); } }; class Shape extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } var options_render = this.props.options.map( (option) => { return <FormGroup controlId="options-step" key={option.title}> <Col componentClass={ControlLabel} sm={4}> {option.title} </Col> <Col sm={8}> <FormControl type={option.type ? option.type : "number"} step={option.step ? option.step : 1} value={option.value()} onChange={(event) => { option.onChange(event) }} onKeyDown={disableEnter}/> </Col> </FormGroup> }); var options_list_render = undefined; if (this.props.options.length >= 1) { options_list_render = <div className="shape-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <p>See <a target="_blank" rel="noopener noreferrer" href={this.props.link}>{this.props.link}</a> for ideas</p> {options_render} </Form> </Panel> </div> } return ( <div className="shape"> <ListGroupItem className={activeClassName} onClick={this.props.clicked}>{this.props.name}</ListGroupItem> {options_list_render} </div> ) } } const shapeListProps = (state, ownProps) => { return { shapes: state.shapes.shapes, polygonSides: state.shapes.polygonSides, starPoints: state.shapes.starPoints, starRatio: state.shapes.starRatio, circleLobes: state.shapes.circleLobes, reuleauxSides: state.shapes.reuleauxSides, epicycloidA: state.shapes.epicycloidA, epicycloidB: state.shapes.epicycloidB, hypocycloidA: state.shapes.hypocycloidA, hypocycloidB: state.shapes.hypocycloidB, roseN: state.shapes.roseN, roseD: state.shapes.roseD, inputText: state.shapes.inputText, currentShape: state.shapes.currentShape, startingSize: state.shapes.startingSize, x_offset: state.transform.xformOffsetX, y_offset: state.transform.xformOffsetY, } } const shapeListDispatch = (dispatch, ownProps) => { return { addShape: (shape) => { dispatch(addShape(shape)); }, setShape: (name) => { dispatch(setShape(name)); }, onPolygonSizeChange: (event) => { dispatch(setShapePolygonSides(event.target.value)); }, onStarPointsChange: (event) => { dispatch(setShapeStarPoints(event.target.value)); }, onStarRatioChange: (event) => { dispatch(setShapeStarRatio(event.target.value)); }, onCircleLobesChange: (event) => { dispatch(setShapeCircleLobes(event.target.value)); }, onReuleauxSidesChange: (event) => { dispatch(setShapeReuleauxSides(event.target.value)); }, onepicycloidAChange: (event) => { dispatch(setShapeepicycloidA(event.target.value)); }, onepicycloidBChange: (event) => { dispatch(setShapeepicycloidB(event.target.value)); }, onhypocycloidAChange: (event) => { dispatch(setShapehypocycloidA(event.target.value)); }, onhypocycloidBChange: (event) => { dispatch(setShapehypocycloidB(event.target.value)); }, onRoseNChange: (event) => { dispatch(setShapeRoseN(event.target.value)); }, onRoseDChange: (event) => { dispatch(setShapeRoseD(event.target.value)); }, onInputTextChange: (event) => { dispatch(setShapeInputText(event.target.value)); }, onSizeChange: (event) => { dispatch(setShapeSize(event.target.value)); }, onOffsetXChange: (event) => { dispatch(setXFormOffsetX(event.target.value)); }, onOffsetYChange: (event) => { dispatch(setXFormOffsetY(event.target.value)); }, } } class ShapeList extends Component { constructor(props) { super(props) this.props.addShape({ name: "Polygon", vertices: (state) => { let points = []; for (let i=0; i<state.shapes.polygonSides; i++) { let angle = Math.PI * 2.0 / state.shapes.polygonSides * (0.5 + i); points.push(Vertex(Math.cos(angle), Math.sin(angle))) } return points; }, options: [ { title: "Number of Sides", value: () => { return this.props.polygonSides }, onChange: this.props.onPolygonSizeChange, }, ], }); this.props.addShape({ name: "Star", vertices: (state) => { let star_points = []; for (let i=0; i<state.shapes.starPoints * 2; i++) { let angle = Math.PI * 2.0 / (2.0 * state.shapes.starPoints) * i; let star_scale = 1.0; if (i % 2 === 0) { star_scale *= state.shapes.starRatio; } star_points.push(Vertex(star_scale * Math.cos(angle), star_scale * Math.sin(angle))) } return star_points }, options: [ { title: "Number of Points", value: () => { return this.props.starPoints }, onChange: this.props.onStarPointsChange, }, { title: "Size of Points", value: () => { return this.props.starRatio }, onChange: this.props.onStarRatioChange, step: 0.05, }, ], }); this.props.addShape({ name: "Circle", vertices: (state) => { let circle_points = [] for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i circle_points.push(Vertex(Math.cos(angle), Math.sin(state.shapes.circleLobes * angle)/state.shapes.circleLobes)) } return circle_points }, options: [ { title: "Number of Lobes", value: () => { return this.props.circleLobes }, onChange: this.props.onCircleLobesChange, }, ], }); this.props.addShape({ name: "Heart", vertices: (state) => { let heart_points = [] for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i // heart equation from: http://mathworld.wolfram.com/HeartCurve.html heart_points.push(Vertex(1.0 * Math.pow(Math.sin(angle), 3), 13.0/16.0 * Math.cos(angle) + -5.0/16.0 * Math.cos(2.0 * angle) + -2.0/16.0 * Math.cos(3.0 * angle) + -1.0/16.0 * Math.cos(4.0 * angle))) } return heart_points }, options: [ ], }); this.props.addShape({ name: "Reuleaux", vertices: (state) => { let points = [] // Construct an equalateral triangle let corners = [] // Initial location at PI/2 let angle = Math.PI/2.0; // How much of the circle in one side? let coverageAngle = Math.PI/state.shapes.reuleauxSides; let halfCoverageAngle = 0.5 * coverageAngle; for (let c=0; c<state.shapes.reuleauxSides; c++) { let startAngle = angle + Math.PI - halfCoverageAngle; corners.push( [Vertex(Math.cos(angle), Math.sin(angle)), startAngle] ); angle += 2.0 * Math.PI / state.shapes.reuleauxSides; } let length = 0.5 / Math.cos(Math.PI/2.0/state.shapes.reuleauxSides); for (let corn=0; corn < corners.length; corn++) { for (let i=0; i<128; i++) { let angle = coverageAngle * (i / 128.0) + corners[corn][1]; points.push(Vertex(length * corners[corn][0].x + Math.cos(angle), length * corners[corn][0].y + Math.sin(angle))); } } return points; }, options: [ { title: "Number of sides", value: () => { return this.props.reuleauxSides }, onChange: this.props.onReuleauxSidesChange, step: 1, }, ], }); this.props.addShape( { name: "Clover", link: "http://mathworld.wolfram.com/Epicycloid.html", vertices: (state) => { let points = [] let a = parseFloat(state.shapes.epicycloidA) let b = parseFloat(state.shapes.epicycloidB) for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i points.push(Vertex(0.5 * (a + b) * Math.cos(angle) - 0.5 * b * Math.cos(((a + b) / b) * angle), 0.5 * (a + b) * Math.sin(angle) - 0.5 * b * Math.sin(((a + b) / b) * angle))) } return points }, options: [ { title: "Large circle radius", value: () => { return this.props.epicycloidA }, onChange: this.props.onepicycloidAChange, step: 0.1, }, { title: "Small circle radius", value: () => { return this.props.epicycloidB }, onChange: this.props.onepicycloidBChange, step: 0.1, }, ], }); this.props.addShape( { name: "Web", link: "http://mathworld.wolfram.com/Hypocycloid.html", vertices: (state) => { let points = [] let a = parseFloat(state.shapes.hypocycloidA) let b = parseFloat(state.shapes.hypocycloidB) for (let i=0; i<128; i++) { let angle = Math.PI * 2.0 / 128.0 * i points.push(Vertex(1.0 * (a - b) * Math.cos(angle) + b * Math.cos(((a - b) / b) * angle), 1.0 * (a - b) * Math.sin(angle) - b * Math.sin(((a - b) / b) * angle))) } return points }, options: [ { title: "Large circle radius", value: () => { return this.props.hypocycloidA }, onChange: this.props.onhypocycloidAChange, step: 0.1, }, { title: "Small circle radius", value: () => { return this.props.hypocycloidB }, onChange: this.props.onhypocycloidBChange, step: 0.1, }, ], }); this.props.addShape({ name: "Rose", link: "http://mathworld.wolfram.com/Rose.html", vertices: (state) => { let points = [] let a = 2 let n = parseInt(state.shapes.roseN) let d = parseInt(state.shapes.roseD) let p = (n * d % 2 === 0) ? 2 : 1 let thetaClose = d * p * 32 * n; let resolution = 64 * n; for (let i=0; i<thetaClose+1; i++) { let theta = Math.PI * 2.0 / (resolution) * i let r = 0.5 * a * Math.sin((n / d) * theta) points.push(Vertex(r * Math.cos(theta), r * Math.sin(theta))) } return points }, options: [ { title: "Numerator", value: () => { return this.props.roseN }, onChange: this.props.onRoseNChange, step: 1, }, { title: "Denominator", value: () => { return this.props.roseD }, onChange: this.props.onRoseDChange, step: 1, }, ], }); this.props.addShape({ name: "Text", vertices: (state) => { let points = []; const under_y = -0.25; points.push(Vertex(0.0, under_y)) let x = 0.0; for (let chi = 0; chi < state.shapes.inputText.length; chi++) { var letter = Font2(state.shapes.inputText[chi]); if (0 < letter.vertices.length) { points.push(Vertex(x + letter.vertices[0].x, under_y)) } for (let vi = 0; vi < letter.vertices.length; vi++) { points.push(Vertex(letter.vertices[vi].x + x, letter.vertices[vi].y)); } if (0 < letter.vertices.length) { points.push(Vertex(x + letter.vertices[letter.vertices.length-1].x, under_y)) } if (chi !== state.shapes.inputText.length-1) { points.push(Vertex(x + letter.max_x, under_y)) } x += letter.max_x; } let widthOffset = x / 2.0; return points.map( (point) => { return Vertex(point.x - widthOffset, point.y); }); }, options: [ { title: "Text", type: "textarea", value: () => { return this.props.inputText }, onChange: this.props.onInputTextChange, }, ], }); this.props.addShape({ name: "V1Engineering", vertices: (state) => { return Vicious1Vertices() }, options: [], }); } render() { let self = this; var shape_render = this.props.shapes.map( (shape) => { return <Shape key={shape.name} name={shape.name} link={shape.link || ""} active={shape.name === self.props.currentShape} options={shape.options} clicked={ () => { self.props.setShape(shape.name); } } /> }); return ( <div className="shapes"> <ListGroup> {shape_render} </ListGroup> <div className="shoptions"> <Panel className="options-panel" collapsible expanded> <Form horizontal> <FormGroup controlId="shape-size"> <Col componentClass={ControlLabel} sm={4}> Starting Size </Col> <Col sm={8}> <FormControl type="number" value={this.props.startingSize} onChange={this.props.onSizeChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="shape-offset"> <Col componentClass={ControlLabel} sm={4}> Offset </Col> <Col componentClass={ControlLabel} sm={1}> X </Col> <Col sm={3}> <FormControl type="number" value={this.props.x_offset} onChange={this.props.onOffsetXChange} onKeyDown={disableEnter}/> </Col> <Col componentClass={ControlLabel} sm={1}> Y </Col> <Col sm={3}> <FormControl type="number" value={this.props.y_offset} onChange={this.props.onOffsetYChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } ShapeList = connect(shapeListProps, shapeListDispatch)(ShapeList) ; const rotateProps = (state, ownProps) => { return { active: state.transform.spinEnabled, value: state.transform.spinValue, switchbacks: state.transform.spinSwitchbacks, } } const rotateDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleSpin()); }, onChange: (event) => { dispatch(setSpin(event.target.value)); }, onSwitchbacksChange: (event) => { dispatch(setSpinSwitchbacks(event.target.value)); }, } } class RotationTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } return ( <div className="rotate"> <ListGroupItem header="Spin" className={activeClassName} onClick={this.props.activeCallback}>Spins the input shape a little bit for each copy</ListGroupItem> <div className="rotate-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="rotate-step"> <Col componentClass={ControlLabel} sm={4}> Spin Step (Can be Negative) </Col> <Col sm={8}> <FormControl type="number" step="0.1" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="rotate-switchbacks"> <Col componentClass={ControlLabel} sm={4}> Switchbacks </Col> <Col sm={8}> <FormControl type="number" step="1" value={this.props.switchbacks} onChange={this.props.onSwitchbacksChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } RotationTransform = connect(rotateProps, rotateDispatch)(RotationTransform) ; const scaleProps = (state, ownProps) => { return { active: state.transform.growEnabled, value: state.transform.growValue, } } const scaleDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleGrow()); }, onChange: (event) => { dispatch(setGrow(event.target.value)); }, } } class ScaleTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } return ( <div className="scale"> <ListGroupItem header="Grow" className={activeClassName} onClick={this.props.activeCallback}>Grows or shrinks the input shape a little bit for each copy</ListGroupItem> <div className="scale-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="scale-step"> <Col componentClass={ControlLabel} sm={4}> Grow Step </Col> <Col sm={8}> <FormControl type="number" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> </div> </div> ) } } ScaleTransform = connect(scaleProps, scaleDispatch)(ScaleTransform) ; const trackProps = (state, ownProps) => { return { active: state.transform.trackEnabled, activeGrow: state.transform.trackGrowEnabled, value: state.transform.trackValue, length: state.transform.trackLength, trackGrow: state.transform.trackGrow, } } const trackDispatch = (dispatch, ownProps) => { return { activeCallback: () => { dispatch(toggleTrack()); }, activeGrowCallback: () => { dispatch(toggleTrackGrow()); }, onChange: (event) => { dispatch(setTrack(event.target.value)); }, onChangeLength: (event) => { dispatch(setTrackLength(event.target.value)); }, onChangeGrow: (event) => { dispatch(setTrackGrow(event.target.value)); }, } } class TrackTransform extends Component { render() { var activeClassName = ""; if (this.props.active) { activeClassName = "active"; } var activeGrowClassName = ""; if (this.props.activeGrow) { activeGrowClassName = "active"; } return ( <div className="track"> <ListGroupItem header="Track" className={activeClassName} onClick={this.props.activeCallback}>Moves the shape along a track (shown in green)</ListGroupItem> <div className="track-options"> <Panel className="options-panel" collapsible expanded={this.props.active}> <Form horizontal> <FormGroup controlId="track-size"> <Col componentClass={ControlLabel} sm={4}> Track Size </Col> <Col sm={8}> <FormControl type="number" value={this.props.value} onChange={this.props.onChange} onKeyDown={disableEnter}/> </Col> </FormGroup> <FormGroup controlId="track-length"> <Col componentClass={ControlLabel} sm={4}> Track Length </Col> <Col sm={8}> <FormControl type="number" value={this.props.length} step="0.05" onChange={this.props.onChangeLength} onKeyDown={disableEnter}/> </Col> </FormGroup> <ListGroupItem header="Grow" className={activeGrowClassName} onClick={this.props.activeGrowCallback}>Grows or shrinks the track a little bit for each step</ListGroupItem> <div className="scale-options"> <Panel className="options-panel" collapsible expanded={this.props.activeGrow}> <FormGroup controlId="scale-step"> <Col componentClass={ControlLabel} sm={4}> Track Grow Step </Col> <Col sm={8}> <FormControl type="number" value={this.props.trackGrow} onChange={this.props.onChangeGrow} onKeyDown={disableEnter}/> </Col> </FormGroup> </Panel> </div> </Form> </Panel> </div> </div> ) } } TrackTransform = connect(trackProps, trackDispatch)(TrackTransform) ; const transformsProps = (state, ownProps) => { return { loops: state.transform.numLoops, } } const transformsDispatch = (dispatch, ownProps) => { return { changeLoops: (event) => { dispatch(setLoops(event.target.value)); }, } } class Transforms extends Component { render() { return ( <div className="transforms"> <Panel className="shapes-panel"> <h4>Input Shapes</h4> <ShapeList /> </Panel> <Panel className="transforms-panel"> <h4>Modifiers</h4> <Panel className="options-panel"> <Form horizontal> <FormGroup controlId="loop-count"> <Col componentClass={ControlLabel} sm={4}> Number of Loops </Col> <Col sm={8}> <FormControl type="number" value={this.props.loops} onChange={this.props.changeLoops} onKeyDown={disableEnter}/> </Col> </FormGroup> </Form> </Panel> <ListGroup> <ScaleTransform /> <RotationTransform /> <TrackTransform /> </ListGroup> </Panel> </div> ); } } Transforms = connect(transformsProps, transformsDispatch)(Transforms); export default Transforms
don't show link text if there is no link
src/inputs/Transforms.js
don't show link text if there is no link
<ide><path>rc/inputs/Transforms.js <ide> }); <ide> <ide> var options_list_render = undefined; <add> var link_render = undefined; <add> <add> if (this.props.link) { <add> link_render = <p>See <a target="_blank" rel="noopener noreferrer" href={this.props.link}>{this.props.link}</a> for ideas</p>; <add> } <ide> <ide> if (this.props.options.length >= 1) { <ide> options_list_render = <ide> <div className="shape-options"> <ide> <Panel className="options-panel" collapsible expanded={this.props.active}> <ide> <Form horizontal> <del> <p>See <a target="_blank" rel="noopener noreferrer" href={this.props.link}>{this.props.link}</a> for ideas</p> <add> {link_render} <ide> {options_render} <ide> </Form> <ide> </Panel>
Java
apache-2.0
1438b6d17e864e1663d8045f9a0520444ba33ca1
0
jstourac/undertow,msfm/undertow,darranl/undertow,pedroigor/undertow,n1hility/undertow,soul2zimate/undertow,aradchykov/undertow,stuartwdouglas/undertow,rhusar/undertow,ctomc/undertow,soul2zimate/undertow,Karm/undertow,pferraro/undertow,undertow-io/undertow,stuartwdouglas/undertow,darranl/undertow,popstr/undertow,n1hility/undertow,jstourac/undertow,undertow-io/undertow,jamezp/undertow,darranl/undertow,marschall/undertow,popstr/undertow,stuartwdouglas/undertow,golovnin/undertow,baranowb/undertow,Karm/undertow,ctomc/undertow,aradchykov/undertow,aldaris/undertow,msfm/undertow,pferraro/undertow,pferraro/undertow,ctomc/undertow,pedroigor/undertow,n1hility/undertow,baranowb/undertow,jstourac/undertow,marschall/undertow,marschall/undertow,undertow-io/undertow,golovnin/undertow,golovnin/undertow,jamezp/undertow,popstr/undertow,rhusar/undertow,msfm/undertow,soul2zimate/undertow,pedroigor/undertow,aradchykov/undertow,Karm/undertow,rhusar/undertow,baranowb/undertow,aldaris/undertow,aldaris/undertow,jamezp/undertow
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.server; import io.undertow.UndertowLogger; import io.undertow.UndertowMessages; import io.undertow.UndertowOptions; import io.undertow.channels.DetachableStreamSinkChannel; import io.undertow.channels.DetachableStreamSourceChannel; import io.undertow.conduits.EmptyStreamSourceConduit; import io.undertow.io.AsyncReceiverImpl; import io.undertow.io.AsyncSenderImpl; import io.undertow.io.BlockingReceiverImpl; import io.undertow.io.BlockingSenderImpl; import io.undertow.io.Receiver; import io.undertow.io.Sender; import io.undertow.io.UndertowInputStream; import io.undertow.io.UndertowOutputStream; import io.undertow.security.api.SecurityContext; import io.undertow.server.handlers.Cookie; import io.undertow.util.AbstractAttachable; import io.undertow.util.AttachmentKey; import io.undertow.util.ConduitFactory; import io.undertow.util.Cookies; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.Methods; import io.undertow.util.NetworkUtils; import io.undertow.util.Protocols; import io.undertow.util.StatusCodes; import org.jboss.logging.Logger; import org.xnio.Buffers; import org.xnio.ChannelExceptionHandler; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.IoUtils; import io.undertow.connector.PooledByteBuffer; import org.xnio.XnioIoThread; import org.xnio.channels.Channels; import org.xnio.channels.Configurable; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.StreamSourceChannel; import org.xnio.conduits.Conduit; import org.xnio.conduits.ConduitStreamSinkChannel; import org.xnio.conduits.ConduitStreamSourceChannel; import org.xnio.conduits.StreamSinkConduit; import org.xnio.conduits.StreamSourceConduit; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.FileChannel; import java.security.AccessController; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import static org.xnio.Bits.allAreSet; import static org.xnio.Bits.anyAreClear; import static org.xnio.Bits.anyAreSet; import static org.xnio.Bits.intBitMask; /** * An HTTP server request/response exchange. An instance of this class is constructed as soon as the request headers are * fully parsed. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class HttpServerExchange extends AbstractAttachable { // immutable state private static final Logger log = Logger.getLogger(HttpServerExchange.class); private static final RuntimePermission SET_SECURITY_CONTEXT = new RuntimePermission("io.undertow.SET_SECURITY_CONTEXT"); private static final String ISO_8859_1 = "ISO-8859-1"; /** * The HTTP reason phrase to send. This is an attachment rather than a field as it is rarely used. If this is not set * a generic description from the RFC is used instead. */ private static final AttachmentKey<String> REASON_PHRASE = AttachmentKey.create(String.class); /** * The attachment key that buffered request data is attached under. */ static final AttachmentKey<PooledByteBuffer[]> BUFFERED_REQUEST_DATA = AttachmentKey.create(PooledByteBuffer[].class); /** * Attachment key that can be used to hold additional request attributes */ public static final AttachmentKey<Map<String, String>> REQUEST_ATTRIBUTES = AttachmentKey.create(Map.class); private final ServerConnection connection; private final HeaderMap requestHeaders; private final HeaderMap responseHeaders; private int exchangeCompletionListenersCount = 0; private ExchangeCompletionListener[] exchangeCompleteListeners; private DefaultResponseListener[] defaultResponseListeners; private Map<String, Deque<String>> queryParameters; private Map<String, Deque<String>> pathParameters; private Map<String, Cookie> requestCookies; private Map<String, Cookie> responseCookies; /** * The actual response channel. May be null if it has not been created yet. */ private WriteDispatchChannel responseChannel; /** * The actual request channel. May be null if it has not been created yet. */ protected ReadDispatchChannel requestChannel; private BlockingHttpExchange blockingHttpExchange; private HttpString protocol; /** * The security context */ private SecurityContext securityContext; // mutable state private int state = 200; private HttpString requestMethod; private String requestScheme; /** * The original request URI. This will include the host name if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -> 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my+File.jsf' */ private String requestURI; /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -> '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my File.jsf' */ private String requestPath; /** * The remaining unresolved portion of request path. If a {@link io.undertow.server.handlers.CanonicalPathHandler} is * installed this will be canonicalised. * <p> * Initially this will be equal to {@link #requestPath}, however it will be modified as handlers resolve the path. */ private String relativePath; /** * The resolved part of the canonical path. */ private String resolvedPath = ""; /** * the query string */ private String queryString = ""; private int requestWrapperCount = 0; private ConduitWrapper<StreamSourceConduit>[] requestWrappers; //we don't allocate these by default, as for get requests they are not used private int responseWrapperCount = 0; private ConduitWrapper<StreamSinkConduit>[] responseWrappers; private Sender sender; private Receiver receiver; private long requestStartTime = -1; /** * The maximum entity size. This can be modified before the request stream is obtained, however once the request * stream is obtained this cannot be modified further. * <p> * The default value for this is determined by the {@link io.undertow.UndertowOptions#MAX_ENTITY_SIZE} option. A value * of 0 indicates that this is unbounded. * <p> * If this entity size is exceeded the request channel will be forcibly closed. * <p> * TODO: integrate this with HTTP 100-continue responses, to make it possible to send a 417 rather than just forcibly * closing the channel. * * @see io.undertow.UndertowOptions#MAX_ENTITY_SIZE */ private long maxEntitySize; /** * When the call stack return this task will be executed by the executor specified in {@link #dispatchExecutor}. * If the executor is null then it will be executed by the XNIO worker. */ private Runnable dispatchTask; /** * The executor that is to be used to dispatch the {@link #dispatchTask}. Note that this is not cleared * between dispatches, so once a request has been dispatched once then all subsequent dispatches will use * the same executor. */ private Executor dispatchExecutor; /** * The number of bytes that have been sent to the remote client. This does not include headers, * only the entity body, and does not take any transfer or content encoding into account. */ private long responseBytesSent = 0; private static final int MASK_RESPONSE_CODE = intBitMask(0, 9); /** * Flag that is set when the response sending begins */ private static final int FLAG_RESPONSE_SENT = 1 << 10; /** * Flag that is sent when the response has been fully written and flushed. */ private static final int FLAG_RESPONSE_TERMINATED = 1 << 11; /** * Flag that is set once the request has been fully read. For zero * length requests this is set immediately. */ private static final int FLAG_REQUEST_TERMINATED = 1 << 12; /** * Flag that is set if this is a persistent connection, and the * connection should be re-used. */ private static final int FLAG_PERSISTENT = 1 << 14; /** * If this flag is set it means that the request has been dispatched, * and will not be ending when the call stack returns. * <p> * This could be because it is being dispatched to a worker thread from * an IO thread, or because resume(Reads/Writes) has been called. */ private static final int FLAG_DISPATCHED = 1 << 15; /** * Flag that is set if the {@link #requestURI} field contains the hostname. */ private static final int FLAG_URI_CONTAINS_HOST = 1 << 16; /** * If this flag is set then the request is current running through a * handler chain. * <p> * This will be true most of the time, this only time this will return * false is when performing async operations outside the scope of a call to * {@link Connectors#executeRootHandler(HttpHandler, HttpServerExchange)}, * such as when performing async IO. * <p> * If this is true then when the call stack returns the exchange will either be dispatched, * or the exchange will be ended. */ private static final int FLAG_IN_CALL = 1 << 17; /** * Flag that indicates that reads should be resumed when the call stack returns. */ private static final int FLAG_SHOULD_RESUME_READS = 1 << 18; /** * Flag that indicates that writes should be resumed when the call stack returns */ private static final int FLAG_SHOULD_RESUME_WRITES = 1 << 19; /** * Flag that indicates that the request channel has been reset, and {@link #getRequestChannel()} can be called again */ private static final int FLAG_REQUEST_RESET= 1 << 20; /** * The source address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress sourceAddress; /** * The destination address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress destinationAddress; public HttpServerExchange(final ServerConnection connection, long maxEntitySize) { this(connection, new HeaderMap(), new HeaderMap(), maxEntitySize); } public HttpServerExchange(final ServerConnection connection) { this(connection, 0); } public HttpServerExchange(final ServerConnection connection, final HeaderMap requestHeaders, final HeaderMap responseHeaders, long maxEntitySize) { this.connection = connection; this.maxEntitySize = maxEntitySize; this.requestHeaders = requestHeaders; this.responseHeaders = responseHeaders; } /** * Get the request protocol string. Normally this is one of the strings listed in {@link Protocols}. * * @return the request protocol string */ public HttpString getProtocol() { return protocol; } /** * Sets the http protocol * * @param protocol */ public HttpServerExchange setProtocol(final HttpString protocol) { this.protocol = protocol; return this; } /** * Determine whether this request conforms to HTTP 0.9. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_0_9}, {@code false} otherwise */ public boolean isHttp09() { return protocol.equals(Protocols.HTTP_0_9); } /** * Determine whether this request conforms to HTTP 1.0. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_0}, {@code false} otherwise */ public boolean isHttp10() { return protocol.equals(Protocols.HTTP_1_0); } /** * Determine whether this request conforms to HTTP 1.1. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_1}, {@code false} otherwise */ public boolean isHttp11() { return protocol.equals(Protocols.HTTP_1_1); } /** * Get the HTTP request method. Normally this is one of the strings listed in {@link io.undertow.util.Methods}. * * @return the HTTP request method */ public HttpString getRequestMethod() { return requestMethod; } /** * Set the HTTP request method. * * @param requestMethod the HTTP request method */ public HttpServerExchange setRequestMethod(final HttpString requestMethod) { this.requestMethod = requestMethod; return this; } /** * Get the request URI scheme. Normally this is one of {@code http} or {@code https}. * * @return the request URI scheme */ public String getRequestScheme() { return requestScheme; } /** * Set the request URI scheme. * * @param requestScheme the request URI scheme */ public HttpServerExchange setRequestScheme(final String requestScheme) { this.requestScheme = requestScheme; return this; } /** * The original request URI. This will include the host name, protocol etc * if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -&gt; 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my+File.jsf' */ public String getRequestURI() { return requestURI; } /** * Sets the request URI * * @param requestURI The new request URI */ public HttpServerExchange setRequestURI(final String requestURI) { this.requestURI = requestURI; return this; } /** * Sets the request URI * * @param requestURI The new request URI * @param containsHost If this is true the request URI contains the host part */ public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; } /** * If a request was submitted to the server with a full URI instead of just a path this * will return true. For example: * <p> * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; true * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; false * * @return <code>true</code> If the request URI contains the host part of the URI */ public boolean isHostIncludedInRequestURI() { return anyAreSet(state, FLAG_URI_CONTAINS_HOST); } /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my File.jsf' */ public String getRequestPath() { return requestPath; } /** * Set the request URI path. * * @param requestPath the request URI path */ public HttpServerExchange setRequestPath(final String requestPath) { this.requestPath = requestPath; return this; } /** * Get the request relative path. This is the path which should be evaluated by the current handler. * <p> * If the {@link io.undertow.server.handlers.CanonicalPathHandler} is installed in the current chain * then this path with be canonicalized * * @return the request relative path */ public String getRelativePath() { return relativePath; } /** * Set the request relative path. * * @param relativePath the request relative path */ public HttpServerExchange setRelativePath(final String relativePath) { this.relativePath = relativePath; return this; } /** * Get the resolved path. * * @return the resolved path */ public String getResolvedPath() { return resolvedPath; } /** * Set the resolved path. * * @param resolvedPath the resolved path */ public HttpServerExchange setResolvedPath(final String resolvedPath) { this.resolvedPath = resolvedPath; return this; } /** * * @return The query string, without the leading ? */ public String getQueryString() { return queryString; } public HttpServerExchange setQueryString(final String queryString) { this.queryString = queryString; return this; } /** * Reconstructs the complete URL as seen by the user. This includes scheme, host name etc, * but does not include query string. * <p> * This is not decoded. */ public String getRequestURL() { if (isHostIncludedInRequestURI()) { return getRequestURI(); } else { return getRequestScheme() + "://" + getHostAndPort() + getRequestURI(); } } /** * Returns the request charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getRequestCharset() { return extractCharset(requestHeaders); } /** * Returns the response charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getResponseCharset() { HeaderMap headers = responseHeaders; return extractCharset(headers); } private String extractCharset(HeaderMap headers) { String contentType = headers.getFirst(Headers.CONTENT_TYPE); if (contentType == null) { return null; } String value = Headers.extractQuotedValueFromHeader(contentType, "charset"); if(value != null) { return value; } return ISO_8859_1; } /** * Return the host that this request was sent to, in general this will be the * value of the Host header, minus the port specifier. * <p> * If this resolves to an IPv6 address it will not be enclosed by square brackets. * Care must be taken when constructing URLs based on this method to ensure IPv6 URLs * are handled correctly. * * @return The host part of the destination address */ public String getHostName() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null) { host = getDestinationAddress().getHostString(); } else { if (host.startsWith("[")) { host = host.substring(1, host.indexOf(']')); } else if (host.indexOf(':') != -1) { host = host.substring(0, host.indexOf(':')); } } return host; } /** * Return the host, and also the port if this request was sent to a non-standard port. In general * this will just be the value of the Host header. * <p> * If this resolves to an IPv6 address it *will* be enclosed by square brackets. The return * value of this method is suitable for inclusion in a URL. * * @return The host and port part of the destination address */ public String getHostAndPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null) { InetSocketAddress address = getDestinationAddress(); host = NetworkUtils.formatPossibleIpv6Address(address.getHostString()); int port = address.getPort(); if (!((getRequestScheme().equals("http") && port == 80) || (getRequestScheme().equals("https") && port == 443))) { host = host + ":" + port; } } return host; } /** * Return the port that this request was sent to. In general this will be the value of the Host * header, minus the host name. * * @return The port part of the destination address */ public int getHostPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host != null) { //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of : final int colonIndex; if (host.startsWith("[")) { colonIndex = host.indexOf(':', host.indexOf(']')); } else { colonIndex = host.indexOf(':'); } if (colonIndex != -1) { return Integer.parseInt(host.substring(colonIndex + 1)); } else { if (getRequestScheme().equals("https")) { return 443; } else if (getRequestScheme().equals("http")) { return 80; } } } return getDestinationAddress().getPort(); } /** * Get the underlying HTTP connection. * * @return the underlying HTTP connection */ public ServerConnection getConnection() { return connection; } public boolean isPersistent() { return anyAreSet(state, FLAG_PERSISTENT); } /** * * @return <code>true</code> If the current thread in the IO thread for the exchange */ public boolean isInIoThread() { return getIoThread() == Thread.currentThread(); } /** * * @return True if this exchange represents an upgrade response */ public boolean isUpgrade() { return getStatusCode() == StatusCodes.SWITCHING_PROTOCOLS; } /** * * @return The number of bytes sent in the entity body */ public long getResponseBytesSent() { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { return responseBytesSent; } else { return 0; //body is not allowed, even if we attempt to write it will be ignored } } public HttpServerExchange setPersistent(final boolean persistent) { if (persistent) { this.state = this.state | FLAG_PERSISTENT; } else { this.state = this.state & ~FLAG_PERSISTENT; } return this; } public boolean isDispatched() { return anyAreSet(state, FLAG_DISPATCHED); } public HttpServerExchange unDispatch() { state &= ~FLAG_DISPATCHED; dispatchTask = null; return this; } /** * */ public HttpServerExchange dispatch() { state |= FLAG_DISPATCHED; return this; } /** * Dispatches this request to the XNIO worker thread pool. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Runnable runnable) { dispatch(null, runnable); return this; } /** * Dispatches this request to the given executor. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Executor executor, final Runnable runnable) { if (executor != null) { this.dispatchExecutor = executor; } if (isInCall()) { state |= FLAG_DISPATCHED; this.dispatchTask = runnable; } else { if (executor == null) { getConnection().getWorker().execute(runnable); } else { executor.execute(runnable); } } return this; } public HttpServerExchange dispatch(final HttpHandler handler) { dispatch(null, handler); return this; } public HttpServerExchange dispatch(final Executor executor, final HttpHandler handler) { final Runnable runnable = new Runnable() { @Override public void run() { Connectors.executeRootHandler(handler, HttpServerExchange.this); } }; dispatch(executor, runnable); return this; } /** * Sets the executor that is used for dispatch operations where no executor is specified. * * @param executor The executor to use */ public HttpServerExchange setDispatchExecutor(final Executor executor) { if (executor == null) { dispatchExecutor = null; } else { dispatchExecutor = executor; } return this; } /** * Gets the current executor that is used for dispatch operations. This may be null * * @return The current dispatch executor */ public Executor getDispatchExecutor() { return dispatchExecutor; } /** * @return The current dispatch task */ Runnable getDispatchTask() { return dispatchTask; } boolean isInCall() { return anyAreSet(state, FLAG_IN_CALL); } HttpServerExchange setInCall(boolean value) { if (value) { state |= FLAG_IN_CALL; } else { state &= ~FLAG_IN_CALL; } return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } if(!getRequestHeaders().contains(Headers.UPGRADE)) { throw UndertowMessages.MESSAGES.notAnUpgradeRequest(); } connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); getResponseHeaders().put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @param productName the product name to report to the client * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); final HeaderMap headers = getResponseHeaders(); headers.put(Headers.UPGRADE, productName); headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * * @param connectListener * @return */ public HttpServerExchange acceptConnectRequest(HttpUpgradeListener connectListener) { if(!getRequestMethod().equals(Methods.CONNECT)) { throw UndertowMessages.MESSAGES.notAConnectRequest(); } connection.setConnectListener(connectListener); return this; } public HttpServerExchange addExchangeCompleteListener(final ExchangeCompletionListener listener) { final int exchangeCompletionListenersCount = this.exchangeCompletionListenersCount++; ExchangeCompletionListener[] exchangeCompleteListeners = this.exchangeCompleteListeners; if (exchangeCompleteListeners == null || exchangeCompleteListeners.length == exchangeCompletionListenersCount) { ExchangeCompletionListener[] old = exchangeCompleteListeners; this.exchangeCompleteListeners = exchangeCompleteListeners = new ExchangeCompletionListener[exchangeCompletionListenersCount + 2]; if(old != null) { System.arraycopy(old, 0, exchangeCompleteListeners, 0, exchangeCompletionListenersCount); } } exchangeCompleteListeners[exchangeCompletionListenersCount] = listener; return this; } public HttpServerExchange addDefaultResponseListener(final DefaultResponseListener listener) { int i = 0; if(defaultResponseListeners == null) { defaultResponseListeners = new DefaultResponseListener[2]; } else { while (i != defaultResponseListeners.length && defaultResponseListeners[i] != null) { ++i; } if (i == defaultResponseListeners.length) { DefaultResponseListener[] old = defaultResponseListeners; defaultResponseListeners = new DefaultResponseListener[defaultResponseListeners.length + 2]; System.arraycopy(old, 0, defaultResponseListeners, 0, old.length); } } defaultResponseListeners[i] = listener; return this; } /** * Get the source address of the HTTP request. * * @return the source address of the HTTP request */ public InetSocketAddress getSourceAddress() { if (sourceAddress != null) { return sourceAddress; } return connection.getPeerAddress(InetSocketAddress.class); } /** * Sets the source address of the HTTP request. If this is not explicitly set * the actual source address of the channel is used. * * @param sourceAddress The address */ public HttpServerExchange setSourceAddress(InetSocketAddress sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * Get the destination address of the HTTP request. * * @return the destination address of the HTTP request */ public InetSocketAddress getDestinationAddress() { if (destinationAddress != null) { return destinationAddress; } return connection.getLocalAddress(InetSocketAddress.class); } /** * Sets the destination address of the HTTP request. If this is not explicitly set * the actual destination address of the channel is used. * * @param destinationAddress The address */ public HttpServerExchange setDestinationAddress(InetSocketAddress destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * Get the request headers. * * @return the request headers */ public HeaderMap getRequestHeaders() { return requestHeaders; } /** * @return The content length of the request, or <code>-1</code> if it has not been set */ public long getRequestContentLength() { String contentLengthString = requestHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Get the response headers. * * @return the response headers */ public HeaderMap getResponseHeaders() { return responseHeaders; } /** * @return The content length of the response, or <code>-1</code> if it has not been set */ public long getResponseContentLength() { String contentLengthString = responseHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Sets the response content length * * @param length The content length */ public HttpServerExchange setResponseContentLength(long length) { if (length == -1) { responseHeaders.remove(Headers.CONTENT_LENGTH); } else { responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length)); } return this; } /** * Returns a mutable map of query parameters. * * @return The query parameters */ public Map<String, Deque<String>> getQueryParameters() { if (queryParameters == null) { queryParameters = new TreeMap<>(); } return queryParameters; } public HttpServerExchange addQueryParam(final String name, final String param) { if (queryParameters == null) { queryParameters = new TreeMap<>(); } Deque<String> list = queryParameters.get(name); if (list == null) { queryParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * Returns a mutable map of path parameters * * @return The path parameters */ public Map<String, Deque<String>> getPathParameters() { if (pathParameters == null) { pathParameters = new TreeMap<>(); } return pathParameters; } public HttpServerExchange addPathParam(final String name, final String param) { if (pathParameters == null) { pathParameters = new TreeMap<>(); } Deque<String> list = pathParameters.get(name); if (list == null) { pathParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * @return A mutable map of request cookies */ public Map<String, Cookie> getRequestCookies() { if (requestCookies == null) { requestCookies = Cookies.parseRequestCookies( getConnection().getUndertowOptions().get(UndertowOptions.MAX_COOKIES, 200), getConnection().getUndertowOptions().get(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, false), requestHeaders.get(Headers.COOKIE)); } return requestCookies; } /** * Sets a response cookie * * @param cookie The cookie */ public HttpServerExchange setResponseCookie(final Cookie cookie) { if (responseCookies == null) { responseCookies = new TreeMap<>(); //hashmap is slow to allocate in JDK7 } responseCookies.put(cookie.getName(), cookie); return this; } /** * @return A mutable map of response cookies */ public Map<String, Cookie> getResponseCookies() { if (responseCookies == null) { responseCookies = new TreeMap<>(); } return responseCookies; } /** * For internal use only * * @return The response cookies, or null if they have not been set yet */ Map<String, Cookie> getResponseCookiesInternal() { return responseCookies; } /** * @return <code>true</code> If the response has already been started */ public boolean isResponseStarted() { return allAreSet(state, FLAG_RESPONSE_SENT); } /** * Get the inbound request. If there is no request body, calling this method * may cause the next request to immediately be processed. The {@link StreamSourceChannel#close()} or {@link StreamSourceChannel#shutdownReads()} * method must be called at some point after the request is processed to prevent resource leakage and to allow * the next request to proceed. Any unread content will be discarded. * * @return the channel for the inbound request, or {@code null} if another party already acquired the channel */ public StreamSourceChannel getRequestChannel() { if (requestChannel != null) { if(anyAreSet(state, FLAG_REQUEST_RESET)) { state &= ~FLAG_REQUEST_RESET; return requestChannel; } return null; } if (anyAreSet(state, FLAG_REQUEST_TERMINATED)) { return requestChannel = new ReadDispatchChannel(new ConduitStreamSourceChannel(Configurable.EMPTY, new EmptyStreamSourceConduit(getIoThread()))); } final ConduitWrapper<StreamSourceConduit>[] wrappers = this.requestWrappers; final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel(); if (wrappers != null) { this.requestWrappers = null; final WrapperConduitFactory<StreamSourceConduit> factory = new WrapperConduitFactory<>(wrappers, requestWrapperCount, sourceChannel.getConduit(), this); sourceChannel.setConduit(factory.create()); } return requestChannel = new ReadDispatchChannel(sourceChannel); } void resetRequestChannel() { state |= FLAG_REQUEST_RESET; } public boolean isRequestChannelAvailable() { return requestChannel == null || anyAreSet(state, FLAG_REQUEST_RESET); } /** * Returns true if the completion handler for this exchange has been invoked, and the request is considered * finished. */ public boolean isComplete() { return allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED); } /** * Returns true if all data has been read from the request, or if there * was not data. * * @return true if the request is complete */ public boolean isRequestComplete() { PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA); if(data != null) { return false; } return allAreSet(state, FLAG_REQUEST_TERMINATED); } /** * @return true if the responses is complete */ public boolean isResponseComplete() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } /** * Force the codec to treat the request as fully read. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ void terminateRequest() { int oldVal = state; if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { // idempotent return; } if (requestChannel != null) { requestChannel.requestDone(); } this.state = oldVal | FLAG_REQUEST_TERMINATED; if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { invokeExchangeCompleteListeners(); } } private void invokeExchangeCompleteListeners() { if (exchangeCompletionListenersCount > 0) { int i = exchangeCompletionListenersCount - 1; ExchangeCompletionListener next = exchangeCompleteListeners[i]; exchangeCompletionListenersCount = -1; next.exchangeEvent(this, new ExchangeCompleteNextListener(exchangeCompleteListeners, this, i)); } else if (exchangeCompletionListenersCount == 0) { exchangeCompletionListenersCount = -1; connection.exchangeComplete(this); } } /** * Get the response channel. The channel must be closed and fully flushed before the next response can be started. * In order to close the channel you must first call {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()}, * and then call {@link org.xnio.channels.StreamSinkChannel#flush()} until it returns true. Alternatively you can * call {@link #endExchange()}, which will close the channel as part of its cleanup. * <p> * Closing a fixed-length response before the corresponding number of bytes has been written will cause the connection * to be reset and subsequent requests to fail; thus it is important to ensure that the proper content length is * delivered when one is specified. The response channel may not be writable until after the response headers have * been sent. * <p> * If this method is not called then an empty or default response body will be used, depending on the response code set. * <p> * The returned channel will begin to write out headers when the first write request is initiated, or when * {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()} is called on the channel with no content being written. * Once the channel is acquired, however, the response code and headers may not be modified. * <p> * * @return the response channel, or {@code null} if another party already acquired the channel */ public StreamSinkChannel getResponseChannel() { if (responseChannel != null) { return null; } final ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; this.responseWrappers = null; final ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel(); if (sinkChannel == null) { return null; } if(wrappers != null) { final WrapperStreamSinkConduitFactory factory = new WrapperStreamSinkConduitFactory(wrappers, responseWrapperCount, this, sinkChannel.getConduit()); sinkChannel.setConduit(factory.create()); } else { sinkChannel.setConduit(connection.getSinkConduit(this, sinkChannel.getConduit())); } this.responseChannel = new WriteDispatchChannel(sinkChannel); this.startResponse(); return responseChannel; } /** * Get the response sender. * <p> * For blocking exchanges this will return a sender that uses the underlying output stream. * * @return the response sender, or {@code null} if another party already acquired the channel or the sender * @see #getResponseChannel() */ public Sender getResponseSender() { if (blockingHttpExchange != null) { return blockingHttpExchange.getSender(); } if (sender != null) { return sender; } return sender = new AsyncSenderImpl(this); } public Receiver getRequestReceiver() { if(blockingHttpExchange != null) { return blockingHttpExchange.getReceiver(); } if(receiver != null) { return receiver; } return receiver = new AsyncReceiverImpl(this); } /** * @return <code>true</code> if {@link #getResponseChannel()} has not been called */ public boolean isResponseChannelAvailable() { return responseChannel == null; } /** * Get the status code. * * @see #getStatusCode() * @return the status code */ @Deprecated public int getResponseCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @see #setStatusCode(int) * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ @Deprecated public HttpServerExchange setResponseCode(final int statusCode) { return setStatusCode(statusCode); } /** * Get the status code. * * @return the status code */ public int getStatusCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ public HttpServerExchange setStatusCode(final int statusCode) { if (statusCode < 0 || statusCode > 999) { throw new IllegalArgumentException("Invalid response code"); } int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } this.state = oldVal & ~MASK_RESPONSE_CODE | statusCode & MASK_RESPONSE_CODE; return this; } /** * Sets the HTTP reason phrase. Depending on the protocol this may or may not be honoured. In particular HTTP2 * has removed support for the reason phrase. * * This method should only be used to interact with legacy frameworks that give special meaning to the reason phrase. * * @param message The status message * @return this exchange */ public HttpServerExchange setReasonPhrase(String message) { putAttachment(REASON_PHRASE, message); return this; } /** * * @return The current reason phrase */ public String getReasonPhrase() { return getAttachment(REASON_PHRASE); } /** * Adds a {@link ConduitWrapper} to the request wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addRequestWrapper(final ConduitWrapper<StreamSourceConduit> wrapper) { ConduitWrapper<StreamSourceConduit>[] wrappers = requestWrappers; if (requestChannel != null) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } if (wrappers == null) { wrappers = requestWrappers = new ConduitWrapper[2]; } else if (wrappers.length == requestWrapperCount) { requestWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, requestWrappers, 0, wrappers.length); wrappers = requestWrappers; } wrappers[requestWrapperCount++] = wrapper; return this; } /** * Adds a {@link ConduitWrapper} to the response wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addResponseWrapper(final ConduitWrapper<StreamSinkConduit> wrapper) { ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; if (responseChannel != null) { throw UndertowMessages.MESSAGES.responseChannelAlreadyProvided(); } if(wrappers == null) { this.responseWrappers = wrappers = new ConduitWrapper[2]; } else if (wrappers.length == responseWrapperCount) { responseWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, responseWrappers, 0, wrappers.length); wrappers = responseWrappers; } wrappers[responseWrapperCount++] = wrapper; return this; } /** * Calling this method puts the exchange in blocking mode, and creates a * {@link BlockingHttpExchange} object to store the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking() { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = new DefaultBlockingHttpExchange(this); return old; } /** * Calling this method puts the exchange in blocking mode, using the given * blocking exchange as the source of the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * <p> * Note that this method may be called multiple times with different * exchange objects, to allow handlers to modify the streams * that are being used. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking(final BlockingHttpExchange httpExchange) { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = httpExchange; return old; } /** * Returns true if {@link #startBlocking()} or {@link #startBlocking(BlockingHttpExchange)} has been called. * * @return <code>true</code> If this is a blocking HTTP server exchange */ public boolean isBlocking() { return blockingHttpExchange != null; } /** * @return The input stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public InputStream getInputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getInputStream(); } /** * @return The output stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public OutputStream getOutputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getOutputStream(); } /** * Force the codec to treat the response as fully written. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ HttpServerExchange terminateResponse() { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { // idempotent return this; } responseChannel.responseDone(); this.state = oldVal | FLAG_RESPONSE_TERMINATED; if (anyAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { invokeExchangeCompleteListeners(); } return this; } /** * * @return The request start time, or -1 if this was not recorded */ public long getRequestStartTime() { return requestStartTime; } HttpServerExchange setRequestStartTime(long requestStartTime) { this.requestStartTime = requestStartTime; return this; } /** * Ends the exchange by fully draining the request channel, and flushing the response channel. * <p> * This can result in handoff to an XNIO worker, so after this method is called the exchange should * not be modified by the caller. * <p> * If the exchange is already complete this method is a noop */ public HttpServerExchange endExchange() { final int state = this.state; if (allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED)) { if(blockingHttpExchange != null) { //we still have to close the blocking exchange in this case, IoUtils.safeClose(blockingHttpExchange); } return this; } if(defaultResponseListeners != null) { int i = defaultResponseListeners.length - 1; while (i >= 0) { DefaultResponseListener listener = defaultResponseListeners[i]; if (listener != null) { defaultResponseListeners[i] = null; try { if (listener.handleDefaultResponse(this)) { return this; } } catch (Exception e) { UndertowLogger.REQUEST_LOGGER.debug("Exception running default response listener", e); } } i--; } } if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { connection.terminateRequestChannel(this); } if (blockingHttpExchange != null) { try { //TODO: can we end up in this situation in a IO thread? blockingHttpExchange.close(); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(connection); } } //417 means that we are rejecting the request //so the client should not actually send any data if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { //not really sure what the best thing to do here is //for now we are just going to drain the channel if (requestChannel == null) { getRequestChannel(); } int totalRead = 0; for (; ; ) { try { long read = Channels.drain(requestChannel, Long.MAX_VALUE); totalRead += read; if (read == 0) { //if the response code is 417 this is a rejected continuation request. //however there is a chance the client could have sent the data anyway //so we attempt to drain, and if we have not drained anything then we //assume the server has not sent any data if (getStatusCode() != StatusCodes.EXPECTATION_FAILED || totalRead > 0) { requestChannel.getReadSetter().set(ChannelListeners.drainListener(Long.MAX_VALUE, new ChannelListener<StreamSourceChannel>() { @Override public void handleEvent(final StreamSourceChannel channel) { if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } } }, new ChannelExceptionHandler<StreamSourceChannel>() { @Override public void handleException(final StreamSourceChannel channel, final IOException e) { //make sure the listeners have been invoked //unless the connection has been killed this is a no-op invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception draining request stream", e); IoUtils.safeClose(connection); } } )); requestChannel.resumeReads(); return this; } else { break; } } else if (read == -1) { break; } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); return this; } } } if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } return this; } private void closeAndFlushResponse() { if(!connection.isOpen()) { //not much point trying to flush //make sure the listeners have been invoked invokeExchangeCompleteListeners(); return; } try { if (isResponseChannelAvailable()) { if(!getRequestMethod().equals(Methods.CONNECT) && !(getRequestMethod().equals(Methods.HEAD) && getResponseHeaders().contains(Headers.CONTENT_LENGTH)) && Connectors.isEntityBodyAllowed(this)) { //according to getResponseHeaders().put(Headers.CONTENT_LENGTH, "0"); } getResponseChannel(); } responseChannel.shutdownWrites(); if (!responseChannel.flush()) { responseChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(final StreamSinkChannel channel) { channel.suspendWrites(); channel.getWriteSetter().set(null); } }, new ChannelExceptionHandler<Channel>() { @Override public void handleException(final Channel channel, final IOException exception) { //make sure the listeners have been invoked invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception ending request", exception); IoUtils.safeClose(connection); } } )); responseChannel.resumeWrites(); } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); } } /** * Transmit the response headers. After this method successfully returns, * the response channel may become writable. * <p/> * If this method fails the request and response channels will be closed. * <p/> * This method runs asynchronously. If the channel is writable it will * attempt to write as much of the response header as possible, and then * queue the rest in a listener and return. * <p/> * If future handlers in the chain attempt to write before this is finished * XNIO will just magically sort it out so it works. This is not actually * implemented yet, so we just terminate the connection straight away at * the moment. * <p/> * TODO: make this work properly * * @throws IllegalStateException if the response headers were already sent */ HttpServerExchange startResponse() throws IllegalStateException { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } this.state = oldVal | FLAG_RESPONSE_SENT; log.tracef("Starting to write response for %s", this); return this; } public XnioIoThread getIoThread() { return connection.getIoThread(); } /** * @return The maximum entity size for this exchange */ public long getMaxEntitySize() { return maxEntitySize; } /** * Sets the max entity size for this exchange. This cannot be modified after the request channel has been obtained. * * @param maxEntitySize The max entity size */ public HttpServerExchange setMaxEntitySize(final long maxEntitySize) { if (!isRequestChannelAvailable()) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } this.maxEntitySize = maxEntitySize; connection.maxEntitySizeUpdated(this); return this; } public SecurityContext getSecurityContext() { return securityContext; } public void setSecurityContext(SecurityContext securityContext) { if(System.getSecurityManager() != null) { AccessController.checkPermission(SET_SECURITY_CONTEXT); } this.securityContext = securityContext; } /** * Adds a listener that will be invoked on response commit * * @param listener The response listener */ public void addResponseCommitListener(final ResponseCommitListener listener) { //technically it is possible to modify the exchange after the response conduit has been created //as the response channel should not be retrieved until it is about to be written to //if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() { @Override public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) { listener.beforeCommit(exchange); return factory.create(); } }); } /** * Actually resumes reads or writes, if the relevant method has been called. * * @return <code>true</code> if reads or writes were resumed */ boolean runResumeReadWrite() { boolean ret = false; if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) { responseChannel.runResume(); ret = true; } if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) { requestChannel.runResume(); ret = true; } state &= ~(FLAG_SHOULD_RESUME_READS | FLAG_SHOULD_RESUME_WRITES); return ret; } private static class ExchangeCompleteNextListener implements ExchangeCompletionListener.NextListener { private final ExchangeCompletionListener[] list; private final HttpServerExchange exchange; private int i; public ExchangeCompleteNextListener(final ExchangeCompletionListener[] list, final HttpServerExchange exchange, int i) { this.list = list; this.exchange = exchange; this.i = i; } @Override public void proceed() { if (--i >= 0) { final ExchangeCompletionListener next = list[i]; next.exchangeEvent(exchange, this); } else if(i == -1) { exchange.connection.exchangeComplete(exchange); } } } private static class DefaultBlockingHttpExchange implements BlockingHttpExchange { private InputStream inputStream; private OutputStream outputStream; private Sender sender; private final HttpServerExchange exchange; DefaultBlockingHttpExchange(final HttpServerExchange exchange) { this.exchange = exchange; } public InputStream getInputStream() { if (inputStream == null) { inputStream = new UndertowInputStream(exchange); } return inputStream; } public OutputStream getOutputStream() { if (outputStream == null) { outputStream = new UndertowOutputStream(exchange); } return outputStream; } @Override public Sender getSender() { if (sender == null) { sender = new BlockingSenderImpl(exchange, getOutputStream()); } return sender; } @Override public void close() throws IOException { try { getInputStream().close(); } finally { getOutputStream().close(); } } @Override public Receiver getReceiver() { return new BlockingReceiverImpl(exchange, getInputStream()); } } /** * Channel implementation that is actually provided to clients of the exchange. * <p/> * We do not provide the underlying conduit channel, as this is shared between requests, so we need to make sure that after this request * is done the the channel cannot affect the next request. * <p/> * It also delays a wakeup/resumesWrites calls until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. */ private class WriteDispatchChannel extends DetachableStreamSinkChannel implements StreamSinkChannel { private boolean wakeup; public WriteDispatchChannel(final ConduitStreamSinkChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } @Override public void resumeWrites() { if (isInCall()) { state |= FLAG_SHOULD_RESUME_WRITES; } else if(!isFinished()){ delegate.resumeWrites(); } } @Override public void wakeupWrites() { if (isFinished()) { return; } if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_WRITES; } else { delegate.wakeupWrites(); } } @Override public boolean isWriteResumed() { return anyAreSet(state, FLAG_SHOULD_RESUME_WRITES) || super.isWriteResumed(); } public void runResume() { if (isWriteResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; delegate.wakeupWrites(); } else { delegate.resumeWrites(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } private void invokeListener() { if(writeSetter != null) { getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(WriteDispatchChannel.this, writeSetter.get()); } }); } } @Override public void awaitWritable() throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(); } @Override public void awaitWritable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(time, timeUnit); } @Override public long transferFrom(FileChannel src, long position, long count) throws IOException { long l = super.transferFrom(src, position, count); if(l > 0) { responseBytesSent += l; } return l; } @Override public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException { long l = super.transferFrom(source, count, throughBuffer); if(l > 0) { responseBytesSent += l; } return l; } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.write(srcs, offset, length); responseBytesSent += l; return l; } @Override public long write(ByteBuffer[] srcs) throws IOException { long l = super.write(srcs); responseBytesSent += l; return l; } @Override public int writeFinal(ByteBuffer src) throws IOException { int l = super.writeFinal(src); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.writeFinal(srcs, offset, length); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs) throws IOException { long l = super.writeFinal(srcs); responseBytesSent += l; return l; } @Override public int write(ByteBuffer src) throws IOException { int l = super.write(src); responseBytesSent += l; return l; } } /** * Channel implementation that is actually provided to clients of the exchange. We do not provide the underlying * conduit channel, as this will become the next requests conduit channel, so if a thread is still hanging onto this * exchange it can result in problems. * <p/> * It also delays a readResume call until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. * <p/> * It also handles buffered request data. */ private final class ReadDispatchChannel extends DetachableStreamSourceChannel implements StreamSourceChannel { private boolean wakeup = true; private boolean readsResumed = false; public ReadDispatchChannel(final ConduitStreamSourceChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_REQUEST_TERMINATED); } @Override public void resumeReads() { readsResumed = true; if (isInCall()) { state |= FLAG_SHOULD_RESUME_READS; } else if (!isFinished()) { delegate.resumeReads(); } } public void wakeupReads() { if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_READS; } else { if(isFinished()) { invokeListener(); } else { delegate.wakeupReads(); } } } private void invokeListener() { if(readSetter != null) { getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(ReadDispatchChannel.this, readSetter.get()); } }); } } public void requestDone() { if(delegate instanceof ConduitStreamSourceChannel) { ((ConduitStreamSourceChannel)delegate).setReadListener(null); ((ConduitStreamSourceChannel)delegate).setCloseListener(null); } else { delegate.getReadSetter().set(null); delegate.getCloseSetter().set(null); } } @Override public long transferTo(long position, long count, FileChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(position, count, target); } return target.transferFrom(this, position, count); } @Override public void awaitReadable() throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(); } } @Override public void suspendReads() { readsResumed = false; super.suspendReads(); } @Override public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(count, throughBuffer, target); } //make sure there is no garbage in throughBuffer throughBuffer.position(0); throughBuffer.limit(0); long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { int res = target.write(buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (res == 0) { return copied; } else { copied += res; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.transferTo(count, throughBuffer, target); } else { return copied; } } @Override public void awaitReadable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(time, timeUnit); } } @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dsts, offset, length); } long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dsts, offset, length, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!Buffers.hasRemaining(dsts, offset, length)) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dsts, offset, length); } else { return copied; } } @Override public long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } @Override public boolean isOpen() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return true; } return super.isOpen(); } @Override public void close() throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { for (PooledByteBuffer pooled : buffered) { if (pooled != null) { pooled.close(); } } } removeAttachment(BUFFERED_REQUEST_DATA); super.close(); } @Override public boolean isReadResumed() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return readsResumed; } if(isFinished()) { return false; } return anyAreSet(state, FLAG_SHOULD_RESUME_READS) || super.isReadResumed(); } @Override public int read(ByteBuffer dst) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dst); } int copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dst, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!dst.hasRemaining()) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dst); } else { return copied; } } public void runResume() { if (isReadResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; delegate.wakeupReads(); } else { delegate.resumeReads(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } } public static class WrapperStreamSinkConduitFactory implements ConduitFactory<StreamSinkConduit> { private final HttpServerExchange exchange; private final ConduitWrapper<StreamSinkConduit>[] wrappers; private int position; private final StreamSinkConduit first; public WrapperStreamSinkConduitFactory(ConduitWrapper<StreamSinkConduit>[] wrappers, int wrapperCount, HttpServerExchange exchange, StreamSinkConduit first) { this.wrappers = wrappers; this.exchange = exchange; this.first = first; this.position = wrapperCount - 1; } @Override public StreamSinkConduit create() { if (position == -1) { return exchange.getConnection().getSinkConduit(exchange, first); } else { return wrappers[position--].wrap(this, exchange); } } } public static class WrapperConduitFactory<T extends Conduit> implements ConduitFactory<T> { private final HttpServerExchange exchange; private final ConduitWrapper<T>[] wrappers; private int position; private T first; public WrapperConduitFactory(ConduitWrapper<T>[] wrappers, int wrapperCount, T first, HttpServerExchange exchange) { this.wrappers = wrappers; this.exchange = exchange; this.position = wrapperCount - 1; this.first = first; } @Override public T create() { if (position == -1) { return first; } else { return wrappers[position--].wrap(this, exchange); } } } @Override public String toString() { return "HttpServerExchange{ " + getRequestMethod().toString() + " " + getRequestURI() + " request " + requestHeaders + " response " + responseHeaders + '}'; } }
core/src/main/java/io/undertow/server/HttpServerExchange.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.server; import io.undertow.UndertowLogger; import io.undertow.UndertowMessages; import io.undertow.UndertowOptions; import io.undertow.channels.DetachableStreamSinkChannel; import io.undertow.channels.DetachableStreamSourceChannel; import io.undertow.conduits.EmptyStreamSourceConduit; import io.undertow.io.AsyncReceiverImpl; import io.undertow.io.AsyncSenderImpl; import io.undertow.io.BlockingReceiverImpl; import io.undertow.io.BlockingSenderImpl; import io.undertow.io.Receiver; import io.undertow.io.Sender; import io.undertow.io.UndertowInputStream; import io.undertow.io.UndertowOutputStream; import io.undertow.security.api.SecurityContext; import io.undertow.server.handlers.Cookie; import io.undertow.util.AbstractAttachable; import io.undertow.util.AttachmentKey; import io.undertow.util.ConduitFactory; import io.undertow.util.Cookies; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.Methods; import io.undertow.util.NetworkUtils; import io.undertow.util.Protocols; import io.undertow.util.StatusCodes; import org.jboss.logging.Logger; import org.xnio.Buffers; import org.xnio.ChannelExceptionHandler; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.IoUtils; import io.undertow.connector.PooledByteBuffer; import org.xnio.XnioIoThread; import org.xnio.channels.Channels; import org.xnio.channels.Configurable; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.StreamSourceChannel; import org.xnio.conduits.Conduit; import org.xnio.conduits.ConduitStreamSinkChannel; import org.xnio.conduits.ConduitStreamSourceChannel; import org.xnio.conduits.StreamSinkConduit; import org.xnio.conduits.StreamSourceConduit; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.FileChannel; import java.security.AccessController; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import static org.xnio.Bits.allAreSet; import static org.xnio.Bits.anyAreClear; import static org.xnio.Bits.anyAreSet; import static org.xnio.Bits.intBitMask; /** * An HTTP server request/response exchange. An instance of this class is constructed as soon as the request headers are * fully parsed. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class HttpServerExchange extends AbstractAttachable { // immutable state private static final Logger log = Logger.getLogger(HttpServerExchange.class); private static final RuntimePermission SET_SECURITY_CONTEXT = new RuntimePermission("io.undertow.SET_SECURITY_CONTEXT"); private static final String ISO_8859_1 = "ISO-8859-1"; /** * The HTTP reason phrase to send. This is an attachment rather than a field as it is rarely used. If this is not set * a generic description from the RFC is used instead. */ private static final AttachmentKey<String> REASON_PHRASE = AttachmentKey.create(String.class); /** * The attachment key that buffered request data is attached under. */ static final AttachmentKey<PooledByteBuffer[]> BUFFERED_REQUEST_DATA = AttachmentKey.create(PooledByteBuffer[].class); /** * Attachment key that can be used to hold additional request attributes */ public static final AttachmentKey<Map<String, String>> REQUEST_ATTRIBUTES = AttachmentKey.create(Map.class); private final ServerConnection connection; private final HeaderMap requestHeaders; private final HeaderMap responseHeaders; private int exchangeCompletionListenersCount = 0; private ExchangeCompletionListener[] exchangeCompleteListeners; private DefaultResponseListener[] defaultResponseListeners; private Map<String, Deque<String>> queryParameters; private Map<String, Deque<String>> pathParameters; private Map<String, Cookie> requestCookies; private Map<String, Cookie> responseCookies; /** * The actual response channel. May be null if it has not been created yet. */ private WriteDispatchChannel responseChannel; /** * The actual request channel. May be null if it has not been created yet. */ protected ReadDispatchChannel requestChannel; private BlockingHttpExchange blockingHttpExchange; private HttpString protocol; /** * The security context */ private SecurityContext securityContext; // mutable state private int state = 200; private HttpString requestMethod; private String requestScheme; /** * The original request URI. This will include the host name if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -> 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my+File.jsf' */ private String requestURI; /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -> '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my File.jsf' */ private String requestPath; /** * The remaining unresolved portion of request path. If a {@link io.undertow.server.handlers.CanonicalPathHandler} is * installed this will be canonicalised. * <p> * Initially this will be equal to {@link #requestPath}, however it will be modified as handlers resolve the path. */ private String relativePath; /** * The resolved part of the canonical path. */ private String resolvedPath = ""; /** * the query string */ private String queryString = ""; private int requestWrapperCount = 0; private ConduitWrapper<StreamSourceConduit>[] requestWrappers; //we don't allocate these by default, as for get requests they are not used private int responseWrapperCount = 0; private ConduitWrapper<StreamSinkConduit>[] responseWrappers; private Sender sender; private Receiver receiver; private long requestStartTime = -1; /** * The maximum entity size. This can be modified before the request stream is obtained, however once the request * stream is obtained this cannot be modified further. * <p> * The default value for this is determined by the {@link io.undertow.UndertowOptions#MAX_ENTITY_SIZE} option. A value * of 0 indicates that this is unbounded. * <p> * If this entity size is exceeded the request channel will be forcibly closed. * <p> * TODO: integrate this with HTTP 100-continue responses, to make it possible to send a 417 rather than just forcibly * closing the channel. * * @see io.undertow.UndertowOptions#MAX_ENTITY_SIZE */ private long maxEntitySize; /** * When the call stack return this task will be executed by the executor specified in {@link #dispatchExecutor}. * If the executor is null then it will be executed by the XNIO worker. */ private Runnable dispatchTask; /** * The executor that is to be used to dispatch the {@link #dispatchTask}. Note that this is not cleared * between dispatches, so once a request has been dispatched once then all subsequent dispatches will use * the same executor. */ private Executor dispatchExecutor; /** * The number of bytes that have been sent to the remote client. This does not include headers, * only the entity body, and does not take any transfer or content encoding into account. */ private long responseBytesSent = 0; private static final int MASK_RESPONSE_CODE = intBitMask(0, 9); /** * Flag that is set when the response sending begins */ private static final int FLAG_RESPONSE_SENT = 1 << 10; /** * Flag that is sent when the response has been fully written and flushed. */ private static final int FLAG_RESPONSE_TERMINATED = 1 << 11; /** * Flag that is set once the request has been fully read. For zero * length requests this is set immediately. */ private static final int FLAG_REQUEST_TERMINATED = 1 << 12; /** * Flag that is set if this is a persistent connection, and the * connection should be re-used. */ private static final int FLAG_PERSISTENT = 1 << 14; /** * If this flag is set it means that the request has been dispatched, * and will not be ending when the call stack returns. * <p> * This could be because it is being dispatched to a worker thread from * an IO thread, or because resume(Reads/Writes) has been called. */ private static final int FLAG_DISPATCHED = 1 << 15; /** * Flag that is set if the {@link #requestURI} field contains the hostname. */ private static final int FLAG_URI_CONTAINS_HOST = 1 << 16; /** * If this flag is set then the request is current running through a * handler chain. * <p> * This will be true most of the time, this only time this will return * false is when performing async operations outside the scope of a call to * {@link Connectors#executeRootHandler(HttpHandler, HttpServerExchange)}, * such as when performing async IO. * <p> * If this is true then when the call stack returns the exchange will either be dispatched, * or the exchange will be ended. */ private static final int FLAG_IN_CALL = 1 << 17; /** * Flag that indicates that reads should be resumed when the call stack returns. */ private static final int FLAG_SHOULD_RESUME_READS = 1 << 18; /** * Flag that indicates that writes should be resumed when the call stack returns */ private static final int FLAG_SHOULD_RESUME_WRITES = 1 << 19; /** * Flag that indicates that the request channel has been reset, and {@link #getRequestChannel()} can be called again */ private static final int FLAG_REQUEST_RESET= 1 << 20; /** * The source address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress sourceAddress; /** * The destination address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress destinationAddress; public HttpServerExchange(final ServerConnection connection, long maxEntitySize) { this(connection, new HeaderMap(), new HeaderMap(), maxEntitySize); } public HttpServerExchange(final ServerConnection connection) { this(connection, 0); } public HttpServerExchange(final ServerConnection connection, final HeaderMap requestHeaders, final HeaderMap responseHeaders, long maxEntitySize) { this.connection = connection; this.maxEntitySize = maxEntitySize; this.requestHeaders = requestHeaders; this.responseHeaders = responseHeaders; } /** * Get the request protocol string. Normally this is one of the strings listed in {@link Protocols}. * * @return the request protocol string */ public HttpString getProtocol() { return protocol; } /** * Sets the http protocol * * @param protocol */ public HttpServerExchange setProtocol(final HttpString protocol) { this.protocol = protocol; return this; } /** * Determine whether this request conforms to HTTP 0.9. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_0_9}, {@code false} otherwise */ public boolean isHttp09() { return protocol.equals(Protocols.HTTP_0_9); } /** * Determine whether this request conforms to HTTP 1.0. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_0}, {@code false} otherwise */ public boolean isHttp10() { return protocol.equals(Protocols.HTTP_1_0); } /** * Determine whether this request conforms to HTTP 1.1. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_1}, {@code false} otherwise */ public boolean isHttp11() { return protocol.equals(Protocols.HTTP_1_1); } /** * Get the HTTP request method. Normally this is one of the strings listed in {@link io.undertow.util.Methods}. * * @return the HTTP request method */ public HttpString getRequestMethod() { return requestMethod; } /** * Set the HTTP request method. * * @param requestMethod the HTTP request method */ public HttpServerExchange setRequestMethod(final HttpString requestMethod) { this.requestMethod = requestMethod; return this; } /** * Get the request URI scheme. Normally this is one of {@code http} or {@code https}. * * @return the request URI scheme */ public String getRequestScheme() { return requestScheme; } /** * Set the request URI scheme. * * @param requestScheme the request URI scheme */ public HttpServerExchange setRequestScheme(final String requestScheme) { this.requestScheme = requestScheme; return this; } /** * The original request URI. This will include the host name, protocol etc * if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -&gt; 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my+File.jsf' */ public String getRequestURI() { return requestURI; } /** * Sets the request URI * * @param requestURI The new request URI */ public HttpServerExchange setRequestURI(final String requestURI) { this.requestURI = requestURI; return this; } /** * Sets the request URI * * @param requestURI The new request URI * @param containsHost If this is true the request URI contains the host part */ public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; } /** * If a request was submitted to the server with a full URI instead of just a path this * will return true. For example: * <p> * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; true * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; false * * @return <code>true</code> If the request URI contains the host part of the URI */ public boolean isHostIncludedInRequestURI() { return anyAreSet(state, FLAG_URI_CONTAINS_HOST); } /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my File.jsf' */ public String getRequestPath() { return requestPath; } /** * Set the request URI path. * * @param requestPath the request URI path */ public HttpServerExchange setRequestPath(final String requestPath) { this.requestPath = requestPath; return this; } /** * Get the request relative path. This is the path which should be evaluated by the current handler. * <p> * If the {@link io.undertow.server.handlers.CanonicalPathHandler} is installed in the current chain * then this path with be canonicalized * * @return the request relative path */ public String getRelativePath() { return relativePath; } /** * Set the request relative path. * * @param relativePath the request relative path */ public HttpServerExchange setRelativePath(final String relativePath) { this.relativePath = relativePath; return this; } /** * Get the resolved path. * * @return the resolved path */ public String getResolvedPath() { return resolvedPath; } /** * Set the resolved path. * * @param resolvedPath the resolved path */ public HttpServerExchange setResolvedPath(final String resolvedPath) { this.resolvedPath = resolvedPath; return this; } /** * * @return The query string, without the leading ? */ public String getQueryString() { return queryString; } public HttpServerExchange setQueryString(final String queryString) { this.queryString = queryString; return this; } /** * Reconstructs the complete URL as seen by the user. This includes scheme, host name etc, * but does not include query string. * <p> * This is not decoded. */ public String getRequestURL() { if (isHostIncludedInRequestURI()) { return getRequestURI(); } else { return getRequestScheme() + "://" + getHostAndPort() + getRequestURI(); } } /** * Returns the request charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getRequestCharset() { return extractCharset(requestHeaders); } /** * Returns the response charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getResponseCharset() { HeaderMap headers = responseHeaders; return extractCharset(headers); } private String extractCharset(HeaderMap headers) { String contentType = headers.getFirst(Headers.CONTENT_TYPE); if (contentType == null) { return null; } String value = Headers.extractQuotedValueFromHeader(contentType, "charset"); if(value != null) { return value; } return ISO_8859_1; } /** * Return the host that this request was sent to, in general this will be the * value of the Host header, minus the port specifier. * <p> * If this resolves to an IPv6 address it will not be enclosed by square brackets. * Care must be taken when constructing URLs based on this method to ensure IPv6 URLs * are handled correctly. * * @return The host part of the destination address */ public String getHostName() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null) { host = getDestinationAddress().getHostString(); } else { if (host.startsWith("[")) { host = host.substring(1, host.indexOf(']')); } else if (host.indexOf(':') != -1) { host = host.substring(0, host.indexOf(':')); } } return host; } /** * Return the host, and also the port if this request was sent to a non-standard port. In general * this will just be the value of the Host header. * <p> * If this resolves to an IPv6 address it *will* be enclosed by square brackets. The return * value of this method is suitable for inclusion in a URL. * * @return The host and port part of the destination address */ public String getHostAndPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null) { InetSocketAddress address = getDestinationAddress(); host = NetworkUtils.formatPossibleIpv6Address(address.getHostString()); int port = address.getPort(); if (!((getRequestScheme().equals("http") && port == 80) || (getRequestScheme().equals("https") && port == 443))) { host = host + ":" + port; } } return host; } /** * Return the port that this request was sent to. In general this will be the value of the Host * header, minus the host name. * * @return The port part of the destination address */ public int getHostPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host != null) { //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of : final int colonIndex; if (host.startsWith("[")) { colonIndex = host.indexOf(':', host.indexOf(']')); } else { colonIndex = host.indexOf(':'); } if (colonIndex != -1) { return Integer.parseInt(host.substring(colonIndex + 1)); } else { if (getRequestScheme().equals("https")) { return 443; } else if (getRequestScheme().equals("http")) { return 80; } } } return getDestinationAddress().getPort(); } /** * Get the underlying HTTP connection. * * @return the underlying HTTP connection */ public ServerConnection getConnection() { return connection; } public boolean isPersistent() { return anyAreSet(state, FLAG_PERSISTENT); } /** * * @return <code>true</code> If the current thread in the IO thread for the exchange */ public boolean isInIoThread() { return getIoThread() == Thread.currentThread(); } /** * * @return True if this exchange represents an upgrade response */ public boolean isUpgrade() { return getStatusCode() == StatusCodes.SWITCHING_PROTOCOLS; } /** * * @return The number of bytes sent in the entity body */ public long getResponseBytesSent() { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { return responseBytesSent; } else { return 0; //body is not allowed, even if we attempt to write it will be ignored } } public HttpServerExchange setPersistent(final boolean persistent) { if (persistent) { this.state = this.state | FLAG_PERSISTENT; } else { this.state = this.state & ~FLAG_PERSISTENT; } return this; } public boolean isDispatched() { return anyAreSet(state, FLAG_DISPATCHED); } public HttpServerExchange unDispatch() { state &= ~FLAG_DISPATCHED; dispatchTask = null; return this; } /** * */ public HttpServerExchange dispatch() { state |= FLAG_DISPATCHED; return this; } /** * Dispatches this request to the XNIO worker thread pool. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Runnable runnable) { dispatch(null, runnable); return this; } /** * Dispatches this request to the given executor. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Executor executor, final Runnable runnable) { if (executor != null) { this.dispatchExecutor = executor; } if (isInCall()) { state |= FLAG_DISPATCHED; this.dispatchTask = runnable; } else { if (executor == null) { getConnection().getWorker().execute(runnable); } else { executor.execute(runnable); } } return this; } public HttpServerExchange dispatch(final HttpHandler handler) { dispatch(null, handler); return this; } public HttpServerExchange dispatch(final Executor executor, final HttpHandler handler) { final Runnable runnable = new Runnable() { @Override public void run() { Connectors.executeRootHandler(handler, HttpServerExchange.this); } }; dispatch(executor, runnable); return this; } /** * Sets the executor that is used for dispatch operations where no executor is specified. * * @param executor The executor to use */ public HttpServerExchange setDispatchExecutor(final Executor executor) { if (executor == null) { dispatchExecutor = null; } else { dispatchExecutor = executor; } return this; } /** * Gets the current executor that is used for dispatch operations. This may be null * * @return The current dispatch executor */ public Executor getDispatchExecutor() { return dispatchExecutor; } /** * @return The current dispatch task */ Runnable getDispatchTask() { return dispatchTask; } boolean isInCall() { return anyAreSet(state, FLAG_IN_CALL); } HttpServerExchange setInCall(boolean value) { if (value) { state |= FLAG_IN_CALL; } else { state &= ~FLAG_IN_CALL; } return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } if(!getRequestHeaders().contains(Headers.UPGRADE)) { throw UndertowMessages.MESSAGES.notAnUpgradeRequest(); } connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); getResponseHeaders().put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @param productName the product name to report to the client * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); final HeaderMap headers = getResponseHeaders(); headers.put(Headers.UPGRADE, productName); headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * * @param connectListener * @return */ public HttpServerExchange acceptConnectRequest(HttpUpgradeListener connectListener) { if(!getRequestMethod().equals(Methods.CONNECT)) { throw UndertowMessages.MESSAGES.notAConnectRequest(); } connection.setConnectListener(connectListener); return this; } public HttpServerExchange addExchangeCompleteListener(final ExchangeCompletionListener listener) { final int exchangeCompletionListenersCount = this.exchangeCompletionListenersCount++; ExchangeCompletionListener[] exchangeCompleteListeners = this.exchangeCompleteListeners; if (exchangeCompleteListeners == null || exchangeCompleteListeners.length == exchangeCompletionListenersCount) { ExchangeCompletionListener[] old = exchangeCompleteListeners; this.exchangeCompleteListeners = exchangeCompleteListeners = new ExchangeCompletionListener[exchangeCompletionListenersCount + 2]; if(old != null) { System.arraycopy(old, 0, exchangeCompleteListeners, 0, exchangeCompletionListenersCount); } } exchangeCompleteListeners[exchangeCompletionListenersCount] = listener; return this; } public HttpServerExchange addDefaultResponseListener(final DefaultResponseListener listener) { int i = 0; if(defaultResponseListeners == null) { defaultResponseListeners = new DefaultResponseListener[2]; } else { while (i != defaultResponseListeners.length && defaultResponseListeners[i] != null) { ++i; } if (i == defaultResponseListeners.length) { DefaultResponseListener[] old = defaultResponseListeners; defaultResponseListeners = new DefaultResponseListener[defaultResponseListeners.length + 2]; System.arraycopy(old, 0, defaultResponseListeners, 0, old.length); } } defaultResponseListeners[i] = listener; return this; } /** * Get the source address of the HTTP request. * * @return the source address of the HTTP request */ public InetSocketAddress getSourceAddress() { if (sourceAddress != null) { return sourceAddress; } return connection.getPeerAddress(InetSocketAddress.class); } /** * Sets the source address of the HTTP request. If this is not explicitly set * the actual source address of the channel is used. * * @param sourceAddress The address */ public HttpServerExchange setSourceAddress(InetSocketAddress sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * Get the source address of the HTTP request. * * @return the source address of the HTTP request */ public InetSocketAddress getDestinationAddress() { if (destinationAddress != null) { return destinationAddress; } return connection.getLocalAddress(InetSocketAddress.class); } /** * Sets the destination address of the HTTP request. If this is not explicitly set * the actual destination address of the channel is used. * * @param destinationAddress The address */ public HttpServerExchange setDestinationAddress(InetSocketAddress destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * Get the request headers. * * @return the request headers */ public HeaderMap getRequestHeaders() { return requestHeaders; } /** * @return The content length of the request, or <code>-1</code> if it has not been set */ public long getRequestContentLength() { String contentLengthString = requestHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Get the response headers. * * @return the response headers */ public HeaderMap getResponseHeaders() { return responseHeaders; } /** * @return The content length of the response, or <code>-1</code> if it has not been set */ public long getResponseContentLength() { String contentLengthString = responseHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Sets the response content length * * @param length The content length */ public HttpServerExchange setResponseContentLength(long length) { if (length == -1) { responseHeaders.remove(Headers.CONTENT_LENGTH); } else { responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length)); } return this; } /** * Returns a mutable map of query parameters. * * @return The query parameters */ public Map<String, Deque<String>> getQueryParameters() { if (queryParameters == null) { queryParameters = new TreeMap<>(); } return queryParameters; } public HttpServerExchange addQueryParam(final String name, final String param) { if (queryParameters == null) { queryParameters = new TreeMap<>(); } Deque<String> list = queryParameters.get(name); if (list == null) { queryParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * Returns a mutable map of path parameters * * @return The path parameters */ public Map<String, Deque<String>> getPathParameters() { if (pathParameters == null) { pathParameters = new TreeMap<>(); } return pathParameters; } public HttpServerExchange addPathParam(final String name, final String param) { if (pathParameters == null) { pathParameters = new TreeMap<>(); } Deque<String> list = pathParameters.get(name); if (list == null) { pathParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * @return A mutable map of request cookies */ public Map<String, Cookie> getRequestCookies() { if (requestCookies == null) { requestCookies = Cookies.parseRequestCookies( getConnection().getUndertowOptions().get(UndertowOptions.MAX_COOKIES, 200), getConnection().getUndertowOptions().get(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, false), requestHeaders.get(Headers.COOKIE)); } return requestCookies; } /** * Sets a response cookie * * @param cookie The cookie */ public HttpServerExchange setResponseCookie(final Cookie cookie) { if (responseCookies == null) { responseCookies = new TreeMap<>(); //hashmap is slow to allocate in JDK7 } responseCookies.put(cookie.getName(), cookie); return this; } /** * @return A mutable map of response cookies */ public Map<String, Cookie> getResponseCookies() { if (responseCookies == null) { responseCookies = new TreeMap<>(); } return responseCookies; } /** * For internal use only * * @return The response cookies, or null if they have not been set yet */ Map<String, Cookie> getResponseCookiesInternal() { return responseCookies; } /** * @return <code>true</code> If the response has already been started */ public boolean isResponseStarted() { return allAreSet(state, FLAG_RESPONSE_SENT); } /** * Get the inbound request. If there is no request body, calling this method * may cause the next request to immediately be processed. The {@link StreamSourceChannel#close()} or {@link StreamSourceChannel#shutdownReads()} * method must be called at some point after the request is processed to prevent resource leakage and to allow * the next request to proceed. Any unread content will be discarded. * * @return the channel for the inbound request, or {@code null} if another party already acquired the channel */ public StreamSourceChannel getRequestChannel() { if (requestChannel != null) { if(anyAreSet(state, FLAG_REQUEST_RESET)) { state &= ~FLAG_REQUEST_RESET; return requestChannel; } return null; } if (anyAreSet(state, FLAG_REQUEST_TERMINATED)) { return requestChannel = new ReadDispatchChannel(new ConduitStreamSourceChannel(Configurable.EMPTY, new EmptyStreamSourceConduit(getIoThread()))); } final ConduitWrapper<StreamSourceConduit>[] wrappers = this.requestWrappers; final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel(); if (wrappers != null) { this.requestWrappers = null; final WrapperConduitFactory<StreamSourceConduit> factory = new WrapperConduitFactory<>(wrappers, requestWrapperCount, sourceChannel.getConduit(), this); sourceChannel.setConduit(factory.create()); } return requestChannel = new ReadDispatchChannel(sourceChannel); } void resetRequestChannel() { state |= FLAG_REQUEST_RESET; } public boolean isRequestChannelAvailable() { return requestChannel == null || anyAreSet(state, FLAG_REQUEST_RESET); } /** * Returns true if the completion handler for this exchange has been invoked, and the request is considered * finished. */ public boolean isComplete() { return allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED); } /** * Returns true if all data has been read from the request, or if there * was not data. * * @return true if the request is complete */ public boolean isRequestComplete() { PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA); if(data != null) { return false; } return allAreSet(state, FLAG_REQUEST_TERMINATED); } /** * @return true if the responses is complete */ public boolean isResponseComplete() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } /** * Force the codec to treat the request as fully read. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ void terminateRequest() { int oldVal = state; if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { // idempotent return; } if (requestChannel != null) { requestChannel.requestDone(); } this.state = oldVal | FLAG_REQUEST_TERMINATED; if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { invokeExchangeCompleteListeners(); } } private void invokeExchangeCompleteListeners() { if (exchangeCompletionListenersCount > 0) { int i = exchangeCompletionListenersCount - 1; ExchangeCompletionListener next = exchangeCompleteListeners[i]; exchangeCompletionListenersCount = -1; next.exchangeEvent(this, new ExchangeCompleteNextListener(exchangeCompleteListeners, this, i)); } else if (exchangeCompletionListenersCount == 0) { exchangeCompletionListenersCount = -1; connection.exchangeComplete(this); } } /** * Get the response channel. The channel must be closed and fully flushed before the next response can be started. * In order to close the channel you must first call {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()}, * and then call {@link org.xnio.channels.StreamSinkChannel#flush()} until it returns true. Alternatively you can * call {@link #endExchange()}, which will close the channel as part of its cleanup. * <p> * Closing a fixed-length response before the corresponding number of bytes has been written will cause the connection * to be reset and subsequent requests to fail; thus it is important to ensure that the proper content length is * delivered when one is specified. The response channel may not be writable until after the response headers have * been sent. * <p> * If this method is not called then an empty or default response body will be used, depending on the response code set. * <p> * The returned channel will begin to write out headers when the first write request is initiated, or when * {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()} is called on the channel with no content being written. * Once the channel is acquired, however, the response code and headers may not be modified. * <p> * * @return the response channel, or {@code null} if another party already acquired the channel */ public StreamSinkChannel getResponseChannel() { if (responseChannel != null) { return null; } final ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; this.responseWrappers = null; final ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel(); if (sinkChannel == null) { return null; } if(wrappers != null) { final WrapperStreamSinkConduitFactory factory = new WrapperStreamSinkConduitFactory(wrappers, responseWrapperCount, this, sinkChannel.getConduit()); sinkChannel.setConduit(factory.create()); } else { sinkChannel.setConduit(connection.getSinkConduit(this, sinkChannel.getConduit())); } this.responseChannel = new WriteDispatchChannel(sinkChannel); this.startResponse(); return responseChannel; } /** * Get the response sender. * <p> * For blocking exchanges this will return a sender that uses the underlying output stream. * * @return the response sender, or {@code null} if another party already acquired the channel or the sender * @see #getResponseChannel() */ public Sender getResponseSender() { if (blockingHttpExchange != null) { return blockingHttpExchange.getSender(); } if (sender != null) { return sender; } return sender = new AsyncSenderImpl(this); } public Receiver getRequestReceiver() { if(blockingHttpExchange != null) { return blockingHttpExchange.getReceiver(); } if(receiver != null) { return receiver; } return receiver = new AsyncReceiverImpl(this); } /** * @return <code>true</code> if {@link #getResponseChannel()} has not been called */ public boolean isResponseChannelAvailable() { return responseChannel == null; } /** * Get the status code. * * @see #getStatusCode() * @return the status code */ @Deprecated public int getResponseCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @see #setStatusCode(int) * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ @Deprecated public HttpServerExchange setResponseCode(final int statusCode) { return setStatusCode(statusCode); } /** * Get the status code. * * @return the status code */ public int getStatusCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ public HttpServerExchange setStatusCode(final int statusCode) { if (statusCode < 0 || statusCode > 999) { throw new IllegalArgumentException("Invalid response code"); } int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } this.state = oldVal & ~MASK_RESPONSE_CODE | statusCode & MASK_RESPONSE_CODE; return this; } /** * Sets the HTTP reason phrase. Depending on the protocol this may or may not be honoured. In particular HTTP2 * has removed support for the reason phrase. * * This method should only be used to interact with legacy frameworks that give special meaning to the reason phrase. * * @param message The status message * @return this exchange */ public HttpServerExchange setReasonPhrase(String message) { putAttachment(REASON_PHRASE, message); return this; } /** * * @return The current reason phrase */ public String getReasonPhrase() { return getAttachment(REASON_PHRASE); } /** * Adds a {@link ConduitWrapper} to the request wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addRequestWrapper(final ConduitWrapper<StreamSourceConduit> wrapper) { ConduitWrapper<StreamSourceConduit>[] wrappers = requestWrappers; if (requestChannel != null) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } if (wrappers == null) { wrappers = requestWrappers = new ConduitWrapper[2]; } else if (wrappers.length == requestWrapperCount) { requestWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, requestWrappers, 0, wrappers.length); wrappers = requestWrappers; } wrappers[requestWrapperCount++] = wrapper; return this; } /** * Adds a {@link ConduitWrapper} to the response wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addResponseWrapper(final ConduitWrapper<StreamSinkConduit> wrapper) { ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; if (responseChannel != null) { throw UndertowMessages.MESSAGES.responseChannelAlreadyProvided(); } if(wrappers == null) { this.responseWrappers = wrappers = new ConduitWrapper[2]; } else if (wrappers.length == responseWrapperCount) { responseWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, responseWrappers, 0, wrappers.length); wrappers = responseWrappers; } wrappers[responseWrapperCount++] = wrapper; return this; } /** * Calling this method puts the exchange in blocking mode, and creates a * {@link BlockingHttpExchange} object to store the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking() { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = new DefaultBlockingHttpExchange(this); return old; } /** * Calling this method puts the exchange in blocking mode, using the given * blocking exchange as the source of the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * <p> * Note that this method may be called multiple times with different * exchange objects, to allow handlers to modify the streams * that are being used. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking(final BlockingHttpExchange httpExchange) { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = httpExchange; return old; } /** * Returns true if {@link #startBlocking()} or {@link #startBlocking(BlockingHttpExchange)} has been called. * * @return <code>true</code> If this is a blocking HTTP server exchange */ public boolean isBlocking() { return blockingHttpExchange != null; } /** * @return The input stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public InputStream getInputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getInputStream(); } /** * @return The output stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public OutputStream getOutputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getOutputStream(); } /** * Force the codec to treat the response as fully written. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ HttpServerExchange terminateResponse() { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { // idempotent return this; } responseChannel.responseDone(); this.state = oldVal | FLAG_RESPONSE_TERMINATED; if (anyAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { invokeExchangeCompleteListeners(); } return this; } /** * * @return The request start time, or -1 if this was not recorded */ public long getRequestStartTime() { return requestStartTime; } HttpServerExchange setRequestStartTime(long requestStartTime) { this.requestStartTime = requestStartTime; return this; } /** * Ends the exchange by fully draining the request channel, and flushing the response channel. * <p> * This can result in handoff to an XNIO worker, so after this method is called the exchange should * not be modified by the caller. * <p> * If the exchange is already complete this method is a noop */ public HttpServerExchange endExchange() { final int state = this.state; if (allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED)) { if(blockingHttpExchange != null) { //we still have to close the blocking exchange in this case, IoUtils.safeClose(blockingHttpExchange); } return this; } if(defaultResponseListeners != null) { int i = defaultResponseListeners.length - 1; while (i >= 0) { DefaultResponseListener listener = defaultResponseListeners[i]; if (listener != null) { defaultResponseListeners[i] = null; try { if (listener.handleDefaultResponse(this)) { return this; } } catch (Exception e) { UndertowLogger.REQUEST_LOGGER.debug("Exception running default response listener", e); } } i--; } } if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { connection.terminateRequestChannel(this); } if (blockingHttpExchange != null) { try { //TODO: can we end up in this situation in a IO thread? blockingHttpExchange.close(); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(connection); } } //417 means that we are rejecting the request //so the client should not actually send any data if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { //not really sure what the best thing to do here is //for now we are just going to drain the channel if (requestChannel == null) { getRequestChannel(); } int totalRead = 0; for (; ; ) { try { long read = Channels.drain(requestChannel, Long.MAX_VALUE); totalRead += read; if (read == 0) { //if the response code is 417 this is a rejected continuation request. //however there is a chance the client could have sent the data anyway //so we attempt to drain, and if we have not drained anything then we //assume the server has not sent any data if (getStatusCode() != StatusCodes.EXPECTATION_FAILED || totalRead > 0) { requestChannel.getReadSetter().set(ChannelListeners.drainListener(Long.MAX_VALUE, new ChannelListener<StreamSourceChannel>() { @Override public void handleEvent(final StreamSourceChannel channel) { if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } } }, new ChannelExceptionHandler<StreamSourceChannel>() { @Override public void handleException(final StreamSourceChannel channel, final IOException e) { //make sure the listeners have been invoked //unless the connection has been killed this is a no-op invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception draining request stream", e); IoUtils.safeClose(connection); } } )); requestChannel.resumeReads(); return this; } else { break; } } else if (read == -1) { break; } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); return this; } } } if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } return this; } private void closeAndFlushResponse() { if(!connection.isOpen()) { //not much point trying to flush //make sure the listeners have been invoked invokeExchangeCompleteListeners(); return; } try { if (isResponseChannelAvailable()) { if(!getRequestMethod().equals(Methods.CONNECT) && !(getRequestMethod().equals(Methods.HEAD) && getResponseHeaders().contains(Headers.CONTENT_LENGTH)) && Connectors.isEntityBodyAllowed(this)) { //according to getResponseHeaders().put(Headers.CONTENT_LENGTH, "0"); } getResponseChannel(); } responseChannel.shutdownWrites(); if (!responseChannel.flush()) { responseChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(final StreamSinkChannel channel) { channel.suspendWrites(); channel.getWriteSetter().set(null); } }, new ChannelExceptionHandler<Channel>() { @Override public void handleException(final Channel channel, final IOException exception) { //make sure the listeners have been invoked invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception ending request", exception); IoUtils.safeClose(connection); } } )); responseChannel.resumeWrites(); } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); } } /** * Transmit the response headers. After this method successfully returns, * the response channel may become writable. * <p/> * If this method fails the request and response channels will be closed. * <p/> * This method runs asynchronously. If the channel is writable it will * attempt to write as much of the response header as possible, and then * queue the rest in a listener and return. * <p/> * If future handlers in the chain attempt to write before this is finished * XNIO will just magically sort it out so it works. This is not actually * implemented yet, so we just terminate the connection straight away at * the moment. * <p/> * TODO: make this work properly * * @throws IllegalStateException if the response headers were already sent */ HttpServerExchange startResponse() throws IllegalStateException { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } this.state = oldVal | FLAG_RESPONSE_SENT; log.tracef("Starting to write response for %s", this); return this; } public XnioIoThread getIoThread() { return connection.getIoThread(); } /** * @return The maximum entity size for this exchange */ public long getMaxEntitySize() { return maxEntitySize; } /** * Sets the max entity size for this exchange. This cannot be modified after the request channel has been obtained. * * @param maxEntitySize The max entity size */ public HttpServerExchange setMaxEntitySize(final long maxEntitySize) { if (!isRequestChannelAvailable()) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } this.maxEntitySize = maxEntitySize; connection.maxEntitySizeUpdated(this); return this; } public SecurityContext getSecurityContext() { return securityContext; } public void setSecurityContext(SecurityContext securityContext) { if(System.getSecurityManager() != null) { AccessController.checkPermission(SET_SECURITY_CONTEXT); } this.securityContext = securityContext; } /** * Adds a listener that will be invoked on response commit * * @param listener The response listener */ public void addResponseCommitListener(final ResponseCommitListener listener) { //technically it is possible to modify the exchange after the response conduit has been created //as the response channel should not be retrieved until it is about to be written to //if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() { @Override public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) { listener.beforeCommit(exchange); return factory.create(); } }); } /** * Actually resumes reads or writes, if the relevant method has been called. * * @return <code>true</code> if reads or writes were resumed */ boolean runResumeReadWrite() { boolean ret = false; if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) { responseChannel.runResume(); ret = true; } if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) { requestChannel.runResume(); ret = true; } state &= ~(FLAG_SHOULD_RESUME_READS | FLAG_SHOULD_RESUME_WRITES); return ret; } private static class ExchangeCompleteNextListener implements ExchangeCompletionListener.NextListener { private final ExchangeCompletionListener[] list; private final HttpServerExchange exchange; private int i; public ExchangeCompleteNextListener(final ExchangeCompletionListener[] list, final HttpServerExchange exchange, int i) { this.list = list; this.exchange = exchange; this.i = i; } @Override public void proceed() { if (--i >= 0) { final ExchangeCompletionListener next = list[i]; next.exchangeEvent(exchange, this); } else if(i == -1) { exchange.connection.exchangeComplete(exchange); } } } private static class DefaultBlockingHttpExchange implements BlockingHttpExchange { private InputStream inputStream; private OutputStream outputStream; private Sender sender; private final HttpServerExchange exchange; DefaultBlockingHttpExchange(final HttpServerExchange exchange) { this.exchange = exchange; } public InputStream getInputStream() { if (inputStream == null) { inputStream = new UndertowInputStream(exchange); } return inputStream; } public OutputStream getOutputStream() { if (outputStream == null) { outputStream = new UndertowOutputStream(exchange); } return outputStream; } @Override public Sender getSender() { if (sender == null) { sender = new BlockingSenderImpl(exchange, getOutputStream()); } return sender; } @Override public void close() throws IOException { try { getInputStream().close(); } finally { getOutputStream().close(); } } @Override public Receiver getReceiver() { return new BlockingReceiverImpl(exchange, getInputStream()); } } /** * Channel implementation that is actually provided to clients of the exchange. * <p/> * We do not provide the underlying conduit channel, as this is shared between requests, so we need to make sure that after this request * is done the the channel cannot affect the next request. * <p/> * It also delays a wakeup/resumesWrites calls until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. */ private class WriteDispatchChannel extends DetachableStreamSinkChannel implements StreamSinkChannel { private boolean wakeup; public WriteDispatchChannel(final ConduitStreamSinkChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } @Override public void resumeWrites() { if (isInCall()) { state |= FLAG_SHOULD_RESUME_WRITES; } else if(!isFinished()){ delegate.resumeWrites(); } } @Override public void wakeupWrites() { if (isFinished()) { return; } if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_WRITES; } else { delegate.wakeupWrites(); } } @Override public boolean isWriteResumed() { return anyAreSet(state, FLAG_SHOULD_RESUME_WRITES) || super.isWriteResumed(); } public void runResume() { if (isWriteResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; delegate.wakeupWrites(); } else { delegate.resumeWrites(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } private void invokeListener() { if(writeSetter != null) { getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(WriteDispatchChannel.this, writeSetter.get()); } }); } } @Override public void awaitWritable() throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(); } @Override public void awaitWritable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(time, timeUnit); } @Override public long transferFrom(FileChannel src, long position, long count) throws IOException { long l = super.transferFrom(src, position, count); if(l > 0) { responseBytesSent += l; } return l; } @Override public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException { long l = super.transferFrom(source, count, throughBuffer); if(l > 0) { responseBytesSent += l; } return l; } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.write(srcs, offset, length); responseBytesSent += l; return l; } @Override public long write(ByteBuffer[] srcs) throws IOException { long l = super.write(srcs); responseBytesSent += l; return l; } @Override public int writeFinal(ByteBuffer src) throws IOException { int l = super.writeFinal(src); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.writeFinal(srcs, offset, length); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs) throws IOException { long l = super.writeFinal(srcs); responseBytesSent += l; return l; } @Override public int write(ByteBuffer src) throws IOException { int l = super.write(src); responseBytesSent += l; return l; } } /** * Channel implementation that is actually provided to clients of the exchange. We do not provide the underlying * conduit channel, as this will become the next requests conduit channel, so if a thread is still hanging onto this * exchange it can result in problems. * <p/> * It also delays a readResume call until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. * <p/> * It also handles buffered request data. */ private final class ReadDispatchChannel extends DetachableStreamSourceChannel implements StreamSourceChannel { private boolean wakeup = true; private boolean readsResumed = false; public ReadDispatchChannel(final ConduitStreamSourceChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_REQUEST_TERMINATED); } @Override public void resumeReads() { readsResumed = true; if (isInCall()) { state |= FLAG_SHOULD_RESUME_READS; } else if (!isFinished()) { delegate.resumeReads(); } } public void wakeupReads() { if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_READS; } else { if(isFinished()) { invokeListener(); } else { delegate.wakeupReads(); } } } private void invokeListener() { if(readSetter != null) { getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(ReadDispatchChannel.this, readSetter.get()); } }); } } public void requestDone() { if(delegate instanceof ConduitStreamSourceChannel) { ((ConduitStreamSourceChannel)delegate).setReadListener(null); ((ConduitStreamSourceChannel)delegate).setCloseListener(null); } else { delegate.getReadSetter().set(null); delegate.getCloseSetter().set(null); } } @Override public long transferTo(long position, long count, FileChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(position, count, target); } return target.transferFrom(this, position, count); } @Override public void awaitReadable() throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(); } } @Override public void suspendReads() { readsResumed = false; super.suspendReads(); } @Override public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(count, throughBuffer, target); } //make sure there is no garbage in throughBuffer throughBuffer.position(0); throughBuffer.limit(0); long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { int res = target.write(buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (res == 0) { return copied; } else { copied += res; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.transferTo(count, throughBuffer, target); } else { return copied; } } @Override public void awaitReadable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(time, timeUnit); } } @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dsts, offset, length); } long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dsts, offset, length, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!Buffers.hasRemaining(dsts, offset, length)) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dsts, offset, length); } else { return copied; } } @Override public long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } @Override public boolean isOpen() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return true; } return super.isOpen(); } @Override public void close() throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { for (PooledByteBuffer pooled : buffered) { if (pooled != null) { pooled.close(); } } } removeAttachment(BUFFERED_REQUEST_DATA); super.close(); } @Override public boolean isReadResumed() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return readsResumed; } if(isFinished()) { return false; } return anyAreSet(state, FLAG_SHOULD_RESUME_READS) || super.isReadResumed(); } @Override public int read(ByteBuffer dst) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dst); } int copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dst, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!dst.hasRemaining()) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dst); } else { return copied; } } public void runResume() { if (isReadResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; delegate.wakeupReads(); } else { delegate.resumeReads(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } } public static class WrapperStreamSinkConduitFactory implements ConduitFactory<StreamSinkConduit> { private final HttpServerExchange exchange; private final ConduitWrapper<StreamSinkConduit>[] wrappers; private int position; private final StreamSinkConduit first; public WrapperStreamSinkConduitFactory(ConduitWrapper<StreamSinkConduit>[] wrappers, int wrapperCount, HttpServerExchange exchange, StreamSinkConduit first) { this.wrappers = wrappers; this.exchange = exchange; this.first = first; this.position = wrapperCount - 1; } @Override public StreamSinkConduit create() { if (position == -1) { return exchange.getConnection().getSinkConduit(exchange, first); } else { return wrappers[position--].wrap(this, exchange); } } } public static class WrapperConduitFactory<T extends Conduit> implements ConduitFactory<T> { private final HttpServerExchange exchange; private final ConduitWrapper<T>[] wrappers; private int position; private T first; public WrapperConduitFactory(ConduitWrapper<T>[] wrappers, int wrapperCount, T first, HttpServerExchange exchange) { this.wrappers = wrappers; this.exchange = exchange; this.position = wrapperCount - 1; this.first = first; } @Override public T create() { if (position == -1) { return first; } else { return wrappers[position--].wrap(this, exchange); } } } @Override public String toString() { return "HttpServerExchange{ " + getRequestMethod().toString() + " " + getRequestURI() + " request " + requestHeaders + " response " + responseHeaders + '}'; } }
Fix mischievous Javadoc comment in io.undertow.server.HttpServerExchange#getDestinationAddress
core/src/main/java/io/undertow/server/HttpServerExchange.java
Fix mischievous Javadoc comment in io.undertow.server.HttpServerExchange#getDestinationAddress
<ide><path>ore/src/main/java/io/undertow/server/HttpServerExchange.java <ide> } <ide> <ide> /** <del> * Get the source address of the HTTP request. <del> * <del> * @return the source address of the HTTP request <add> * Get the destination address of the HTTP request. <add> * <add> * @return the destination address of the HTTP request <ide> */ <ide> public InetSocketAddress getDestinationAddress() { <ide> if (destinationAddress != null) {
Java
apache-2.0
e050a5f76d19094b83a2f0dbc94e9092b6a6f1cb
0
bhargavbhegde7/android-ocr,patrickms/android-ocr,sirojnurulum/android-ocr,yiakwy/android-ocr,luklanis/esr-scanner,didldum/android-ocr,yummy222/android-ocr,bigant88/android-ocr,Drakefrog/android-ocr,zhupengGitHub/android-ocr,nonamejx/DictionaryX,jkalbere/beer-app-ocr,The-Chanman/android-ocr,yummy222/android-ocr,The-Chanman/android-ocr,gelahcem/android-ocr,bhargavbhegde7/android-ocr,bigant88/android-ocr,zhupengGitHub/android-ocr,sirojnurulum/android-ocr,rmtheis/android-ocr,patrickms/android-ocr,rmtheis/android-ocr,Drakefrog/android-ocr,didldum/android-ocr,gelahcem/android-ocr,nonamejx/DictionaryX,yiakwy/android-ocr
/* * Copyright (C) 2008 ZXing authors * Copyright 2011 Robert Theis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.sfsu.cs.orange.ocr; import com.googlecode.tesseract.android.TessBaseAPI; import edu.sfsu.cs.orange.ocr.CaptureActivity; import edu.sfsu.cs.orange.ocr.R; import edu.sfsu.cs.orange.ocr.camera.CameraManager; import edu.sfsu.cs.orange.ocr.OcrResult; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.widget.Toast; /** * This class handles all the messaging which comprises the state machine for capture. * * @author [email protected] (Daniel Switkin) */ final class CaptureActivityHandler extends Handler { private static final String TAG = CaptureActivityHandler.class.getSimpleName(); private final CaptureActivity activity; private final DecodeThread decodeThread; private static State state; private static boolean isAutofocusLoopStarted = false; private enum State { PREVIEW, PREVIEW_FOCUSING, PREVIEW_PAUSED, CONTINUOUS, CONTINUOUS_FOCUSING, CONTINUOUS_PAUSED, CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH, SUCCESS, DONE } CaptureActivityHandler(CaptureActivity activity, TessBaseAPI baseApi, boolean isContinuousModeActive) { this.activity = activity; // Start ourselves capturing previews (and decoding if using continuous recognition mode). CameraManager.get().startPreview(); decodeThread = new DecodeThread(activity, //new ViewfinderResultPointCallback(activity.getViewfinderView()), baseApi); decodeThread.start(); if (isContinuousModeActive) { state = State.CONTINUOUS; // Show the shutter and torch buttons activity.setButtonVisibility(true); // Display a "be patient" message while first recognition request is running activity.setStatusViewForContinuous(); CameraManager.get().requestAutoFocus(this, R.id.auto_focus); restartOcrPreviewAndDecode(); } else { state = State.SUCCESS; // Show the shutter and torch buttons activity.setButtonVisibility(true); restartOcrPreview(); } } @Override public void handleMessage(Message message) { // Messages from the decode handler returning decode results switch (message.what) { case R.id.auto_focus: // When one auto focus pass finishes, start another. This is the closest thing to // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do. // Submit another delayed autofocus request. if (state == State.PREVIEW_FOCUSING || state == State.PREVIEW) { state = State.PREVIEW; requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_FOCUSING || state == State.CONTINUOUS) { state = State.CONTINUOUS; requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.PREVIEW_FOCUSING) { requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_FOCUSING) { requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH) { state = State.CONTINUOUS; requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); restartOcrPreviewAndDecode(); } else { isAutofocusLoopStarted = false; } break; case R.id.user_requested_auto_focus_done: // Reset the state, but don't request more autofocusing. if (state == State.PREVIEW_FOCUSING) { state = State.PREVIEW; } else if (state == State.CONTINUOUS_FOCUSING) { state = State.CONTINUOUS; } else if (state == State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH) { state = State.CONTINUOUS; restartOcrPreviewAndDecode(); } break; case R.id.restart_preview: restartOcrPreview(); break; case R.id.ocr_continuous_decode_failed: DecodeHandler.resetDecodeState(); try { activity.handleOcrContinuousDecode((OcrResultFailure) message.obj); } catch (NullPointerException e) { Log.w(TAG, "got bad OcrResultFailure", e); } if (state == State.CONTINUOUS) { restartOcrPreviewAndDecode(); } else if (state == State.CONTINUOUS_FOCUSING) { state = State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH; } break; case R.id.ocr_continuous_decode_succeeded: DecodeHandler.resetDecodeState(); try { activity.handleOcrContinuousDecode((OcrResult) message.obj); } catch (NullPointerException e) { // Continue } if (state == State.CONTINUOUS) { restartOcrPreviewAndDecode(); } else if (state == State.CONTINUOUS_FOCUSING) { state = State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH; } break; case R.id.ocr_decode_succeeded: state = State.SUCCESS; activity.setShutterButtonClickable(true); activity.handleOcrDecode((OcrResult) message.obj); break; case R.id.ocr_decode_failed: state = State.PREVIEW; activity.setShutterButtonClickable(true); Toast toast = Toast.makeText(activity.getBaseContext(), "OCR failed. Please try again.", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); break; } } void stop() { // TODO See if this should be done by sending a quit message to decodeHandler as is done // below in quitSynchronously(). Log.d(TAG, "Setting state to CONTINUOUS_PAUSED."); state = State.CONTINUOUS_PAUSED; removeMessages(R.id.auto_focus); removeMessages(R.id.ocr_continuous_decode); removeMessages(R.id.ocr_decode); removeMessages(R.id.ocr_continuous_decode_failed); removeMessages(R.id.ocr_continuous_decode_succeeded); // TODO are these removeMessages() calls doing anything? // Freeze the view displayed to the user. // CameraManager.get().stopPreview(); } void resetState() { //Log.d(TAG, "in restart()"); if (state == State.CONTINUOUS_PAUSED) { Log.d(TAG, "Setting state to CONTINUOUS"); state = State.CONTINUOUS; restartOcrPreviewAndDecode(); } } void quitSynchronously() { state = State.DONE; CameraManager cameraManager = CameraManager.get(); if (cameraManager != null) { CameraManager.get().stopPreview(); } //Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); try { //quit.sendToTarget(); // This always gives "sending message to a Handler on a dead thread" // Wait at most half a second; should be enough time, and onPause() will timeout quickly decodeThread.join(500L); } catch (InterruptedException e) { Log.w(TAG, "Caught InterruptedException in quitSyncronously()", e); // continue } catch (RuntimeException e) { Log.w(TAG, "Caught RuntimeException in quitSyncronously()", e); // continue } catch (Exception e) { Log.w(TAG, "Caught unknown Exception in quitSynchronously()", e); } // Be absolutely sure we don't send any queued up messages removeMessages(R.id.auto_focus); removeMessages(R.id.ocr_continuous_decode); removeMessages(R.id.ocr_decode); } // Start the preview, but don't try to OCR anything until the user presses the shutter button. private void restartOcrPreview() { // Display the shutter and torch buttons activity.setButtonVisibility(true); if (state == State.SUCCESS) { state = State.PREVIEW; // Draw the viewfinder. activity.drawViewfinder(); // Start cycling the autofocus if (!isAutofocusLoopStarted) { isAutofocusLoopStarted = true; requestAutofocus(R.id.auto_focus); } } } // Send a decode request for continuous OCR mode private void restartOcrPreviewAndDecode() { // Continue capturing camera frames CameraManager.get().startPreview(); // Continue requesting decode of images CameraManager.get().requestOcrDecode(decodeThread.getHandler(), R.id.ocr_continuous_decode); activity.drawViewfinder(); } private void ocrDecode() { state = State.PREVIEW_PAUSED; CameraManager.get().requestOcrDecode(decodeThread.getHandler(), R.id.ocr_decode); } void hardwareShutterButtonClick() { // Ensure that we're not in continuous recognition mode if (state == State.PREVIEW || state == State.PREVIEW_FOCUSING) { ocrDecode(); } } void shutterButtonClick() { // Disable further clicks on this button until OCR request is finished activity.setShutterButtonClickable(false); ocrDecode(); } private void requestAutofocus(int message) { if (state == State.PREVIEW || state == State.CONTINUOUS){ if (state == State.PREVIEW) { state = State.PREVIEW_FOCUSING; } else if (state == State.CONTINUOUS){ state = State.CONTINUOUS_FOCUSING; } CameraManager.get().requestAutoFocus(this, message); } else { // If we're bumping up against a user-requested focus, enqueue another focus request, // otherwise stop autofocusing until the next restartOcrPreview() if (state == State.PREVIEW_FOCUSING && message == R.id.auto_focus) { //Log.d(TAG, "focusing now, so Requesting a new delayed autofocus"); requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, message); } else if (state == State.CONTINUOUS_FOCUSING && message == R.id.auto_focus) { requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, message); } else if (message == R.id.auto_focus) { isAutofocusLoopStarted = false; } } } void requestDelayedAutofocus(final long delay, final int message) { Handler autofocusHandler = new Handler(); autofocusHandler.postDelayed(new Runnable() { public void run() { requestAutofocus(message); } }, delay); } }
android/src/edu/sfsu/cs/orange/ocr/CaptureActivityHandler.java
/* * Copyright (C) 2008 ZXing authors * Copyright 2011 Robert Theis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.sfsu.cs.orange.ocr; import com.googlecode.tesseract.android.TessBaseAPI; import edu.sfsu.cs.orange.ocr.CaptureActivity; import edu.sfsu.cs.orange.ocr.R; import edu.sfsu.cs.orange.ocr.camera.CameraManager; import edu.sfsu.cs.orange.ocr.OcrResult; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.widget.Toast; /** * This class handles all the messaging which comprises the state machine for capture. * * @author [email protected] (Daniel Switkin) */ final class CaptureActivityHandler extends Handler { private static final String TAG = CaptureActivityHandler.class.getSimpleName(); private final CaptureActivity activity; private final DecodeThread decodeThread; private static State state; private static boolean isAutofocusLoopStarted = false; private enum State { PREVIEW, PREVIEW_FOCUSING, PREVIEW_PAUSED, CONTINUOUS, CONTINUOUS_FOCUSING, CONTINUOUS_PAUSED, CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH, SUCCESS, DONE } CaptureActivityHandler(CaptureActivity activity, TessBaseAPI baseApi, boolean isContinuousModeActive) { this.activity = activity; // Start ourselves capturing previews (and decoding if using continuous recognition mode). CameraManager.get().startPreview(); decodeThread = new DecodeThread(activity, //new ViewfinderResultPointCallback(activity.getViewfinderView()), baseApi); decodeThread.start(); if (isContinuousModeActive) { state = State.CONTINUOUS; // Show the shutter and torch buttons activity.setButtonVisibility(true); // Display a "be patient" message while first recognition request is running activity.setStatusViewForContinuous(); CameraManager.get().requestAutoFocus(this, R.id.auto_focus); restartOcrPreviewAndDecode(); } else { state = State.SUCCESS; // Show the shutter and torch buttons activity.setButtonVisibility(true); restartOcrPreview(); } } @Override public void handleMessage(Message message) { // Messages from the decode handler returning decode results switch (message.what) { case R.id.auto_focus: // When one auto focus pass finishes, start another. This is the closest thing to // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do. // Submit another delayed autofocus request. if (state == State.PREVIEW_FOCUSING || state == State.PREVIEW) { state = State.PREVIEW; requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_FOCUSING || state == State.CONTINUOUS) { state = State.CONTINUOUS; requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.PREVIEW_FOCUSING) { requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_FOCUSING) { requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); } else if (state == State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH) { state = State.CONTINUOUS; requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, R.id.auto_focus); restartOcrPreviewAndDecode(); } else { isAutofocusLoopStarted = false; } break; case R.id.user_requested_auto_focus_done: // Reset the state, but don't request more autofocusing. if (state == State.PREVIEW_FOCUSING) { state = State.PREVIEW; } else if (state == State.CONTINUOUS_FOCUSING) { state = State.CONTINUOUS; } else if (state == State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH) { state = State.CONTINUOUS; restartOcrPreviewAndDecode(); } break; case R.id.restart_preview: restartOcrPreview(); break; case R.id.ocr_continuous_decode_failed: DecodeHandler.resetDecodeState(); try { activity.handleOcrContinuousDecode((OcrResultFailure) message.obj); } catch (NullPointerException e) { Log.w(TAG, "got bad OcrResultFailure", e); } if (state == State.CONTINUOUS) { restartOcrPreviewAndDecode(); } else if (state == State.CONTINUOUS_FOCUSING) { message = Message.obtain(activity.getHandler(), R.id.ocr_continuous_retry_after_autofocus, true); message.sendToTarget(); } break; case R.id.ocr_continuous_decode_succeeded: DecodeHandler.resetDecodeState(); try { activity.handleOcrContinuousDecode((OcrResult) message.obj); } catch (NullPointerException e) { // Continue } if (state == State.CONTINUOUS) { restartOcrPreviewAndDecode(); } else if (state == State.CONTINUOUS_FOCUSING) { state = State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH; } break; case R.id.ocr_decode_succeeded: state = State.SUCCESS; activity.setShutterButtonClickable(true); activity.handleOcrDecode((OcrResult) message.obj); break; case R.id.ocr_decode_failed: state = State.PREVIEW; activity.setShutterButtonClickable(true); Toast toast = Toast.makeText(activity.getBaseContext(), "OCR failed. Please try again.", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); break; } } void stop() { // TODO See if this should be done by sending a quit message to decodeHandler as is done // below in quitSynchronously(). Log.d(TAG, "Setting state to CONTINUOUS_PAUSED."); state = State.CONTINUOUS_PAUSED; removeMessages(R.id.auto_focus); removeMessages(R.id.ocr_continuous_decode); removeMessages(R.id.ocr_decode); removeMessages(R.id.ocr_continuous_decode_failed); removeMessages(R.id.ocr_continuous_decode_succeeded); // TODO are these removeMessages() calls doing anything? // Freeze the view displayed to the user. // CameraManager.get().stopPreview(); } void resetState() { //Log.d(TAG, "in restart()"); if (state == State.CONTINUOUS_PAUSED) { Log.d(TAG, "Setting state to CONTINUOUS"); state = State.CONTINUOUS; restartOcrPreviewAndDecode(); } } void quitSynchronously() { state = State.DONE; CameraManager cameraManager = CameraManager.get(); if (cameraManager != null) { CameraManager.get().stopPreview(); } //Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); try { //quit.sendToTarget(); // This always gives "sending message to a Handler on a dead thread" // Wait at most half a second; should be enough time, and onPause() will timeout quickly decodeThread.join(500L); } catch (InterruptedException e) { Log.w(TAG, "Caught InterruptedException in quitSyncronously()", e); // continue } catch (RuntimeException e) { Log.w(TAG, "Caught RuntimeException in quitSyncronously()", e); // continue } catch (Exception e) { Log.w(TAG, "Caught unknown Exception in quitSynchronously()", e); } // Be absolutely sure we don't send any queued up messages removeMessages(R.id.auto_focus); removeMessages(R.id.ocr_continuous_decode); removeMessages(R.id.ocr_decode); } // Start the preview, but don't try to OCR anything until the user presses the shutter button. private void restartOcrPreview() { // Display the shutter and torch buttons activity.setButtonVisibility(true); if (state == State.SUCCESS) { state = State.PREVIEW; // Draw the viewfinder. activity.drawViewfinder(); // Start cycling the autofocus if (!isAutofocusLoopStarted) { isAutofocusLoopStarted = true; requestAutofocus(R.id.auto_focus); } } } // Send a decode request for continuous OCR mode private void restartOcrPreviewAndDecode() { // Continue capturing camera frames CameraManager.get().startPreview(); // Continue requesting decode of images CameraManager.get().requestOcrDecode(decodeThread.getHandler(), R.id.ocr_continuous_decode); activity.drawViewfinder(); } private void ocrDecode() { state = State.PREVIEW_PAUSED; CameraManager.get().requestOcrDecode(decodeThread.getHandler(), R.id.ocr_decode); } void hardwareShutterButtonClick() { // Ensure that we're not in continuous recognition mode if (state == State.PREVIEW || state == State.PREVIEW_FOCUSING) { ocrDecode(); } } void shutterButtonClick() { // Disable further clicks on this button until OCR request is finished activity.setShutterButtonClickable(false); ocrDecode(); } private void requestAutofocus(int message) { if (state == State.PREVIEW || state == State.CONTINUOUS){ if (state == State.PREVIEW) { state = State.PREVIEW_FOCUSING; } else if (state == State.CONTINUOUS){ state = State.CONTINUOUS_FOCUSING; } CameraManager.get().requestAutoFocus(this, message); } else { // If we're bumping up against a user-requested focus, enqueue another focus request, // otherwise stop autofocusing until the next restartOcrPreview() if (state == State.PREVIEW_FOCUSING && message == R.id.auto_focus) { //Log.d(TAG, "focusing now, so Requesting a new delayed autofocus"); requestDelayedAutofocus(CaptureActivity.PREVIEW_AUTOFOCUS_INTERVAL_MS, message); } else if (state == State.CONTINUOUS_FOCUSING && message == R.id.auto_focus) { requestDelayedAutofocus(CaptureActivity.CONTINUOUS_AUTOFOCUS_INTERVAL_MS, message); } else if (message == R.id.auto_focus) { isAutofocusLoopStarted = false; } } } void requestDelayedAutofocus(final long delay, final int message) { Handler autofocusHandler = new Handler(); autofocusHandler.postDelayed(new Runnable() { public void run() { requestAutofocus(message); } }, delay); } }
delay continuous decoding when autofocus is focusing
android/src/edu/sfsu/cs/orange/ocr/CaptureActivityHandler.java
delay continuous decoding when autofocus is focusing
<ide><path>ndroid/src/edu/sfsu/cs/orange/ocr/CaptureActivityHandler.java <ide> if (state == State.CONTINUOUS) { <ide> restartOcrPreviewAndDecode(); <ide> } else if (state == State.CONTINUOUS_FOCUSING) { <del> message = Message.obtain(activity.getHandler(), R.id.ocr_continuous_retry_after_autofocus, true); <del> message.sendToTarget(); <add> state = State.CONTINUOUS_WAITING_FOR_AUTOFOCUS_TO_FINISH; <ide> } <ide> break; <ide> case R.id.ocr_continuous_decode_succeeded:
Java
apache-2.0
7b1438054cb168118e9954da1354f667678170f3
0
espiegelberg/spring-data-neo4j
/* * Copyright (c) [2011-2016] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd." * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with * separate copyright notices and license terms. Your use of the source * code for these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. * */ package org.springframework.data.neo4j.conversion; import org.neo4j.ogm.MetaData; import org.neo4j.ogm.metadata.ClassInfo; import org.neo4j.ogm.metadata.FieldInfo; import org.neo4j.ogm.metadata.MethodInfo; import org.neo4j.ogm.typeconversion.AttributeConverter; import org.neo4j.ogm.typeconversion.ConversionCallback; import org.neo4j.ogm.typeconversion.ProxyAttributeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.convert.converter.Converter; import java.lang.reflect.ParameterizedType; /** * Specialisation of {@link GenericConversionService} that creates Spring-compatible converters from those known by the mapping * {@link MetaData}, allowing the OGM type converters to be reused throughout a Spring application. * * @author Adam George * @author Luanne Misquitta */ public class MetaDataDrivenConversionService extends GenericConversionService implements ConversionCallback { private static final Logger logger = LoggerFactory.getLogger(MetaDataDrivenConversionService.class); /** * Constructs a new {@link MetaDataDrivenConversionService} based on the given {@link MetaData}. * * @param metaData The OGM {@link MetaData} from which to elicit type converters configured in the underlying object-graph * mapping layer */ public MetaDataDrivenConversionService(MetaData metaData) { metaData.registerConversionCallback(this); for (ClassInfo classInfo : metaData.persistentEntities()) { for (FieldInfo fieldInfo : classInfo.propertyFields()) { if (fieldInfo.hasConverter()) { addWrappedConverter(fieldInfo.converter()); } } // TODO: do we need to check the setters too or are programmers obliged to annotate both? for (MethodInfo methodInfo : classInfo.propertyGetters()) { if (methodInfo.hasConverter()) { addWrappedConverter(methodInfo.converter()); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void addWrappedConverter(final AttributeConverter attributeConverter) { if (attributeConverter instanceof ProxyAttributeConverter) { return; } Converter toGraphConverter = new Converter() { @Override public Object convert(Object source) { return attributeConverter.toGraphProperty(source); } }; Converter toEntityConverter = new Converter() { @Override public Object convert(Object source) { return attributeConverter.toEntityAttribute(source); } }; ParameterizedType pt = (ParameterizedType) attributeConverter.getClass().getGenericInterfaces()[0]; Class<?> sourceType, targetType; if (pt.getActualTypeArguments()[0] instanceof Class) { sourceType = (Class<?>) pt.getActualTypeArguments()[0]; } else { //the argument may be a Collection for example sourceType = (Class<?>)((ParameterizedType) pt.getActualTypeArguments()[0]).getActualTypeArguments()[0]; } if (pt.getActualTypeArguments()[1] instanceof Class) { targetType = (Class<?>) pt.getActualTypeArguments()[1]; } else { targetType = (Class<?>)((ParameterizedType) pt.getActualTypeArguments()[1]).getActualTypeArguments()[1]; } if (canConvert(sourceType, targetType) && canConvert(targetType, sourceType)) { logger.info("Not adding Spring-compatible converter for " + attributeConverter.getClass() + " because one that does the same job has already been registered with the ConversionService."); } else { // It could be argued that this is wrong as it potentially overrides a registered converted that doesn't handle // both directions, but I've decided that it's better to ensure the same converter is used for load and save. addConverter(sourceType, targetType, toGraphConverter); addConverter(targetType, sourceType, toEntityConverter); } } @Override public <T> T convert(Class<T> targetType, Object value) { if (value == null) { return null; } return convert(value, targetType); } }
spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java
/* * Copyright (c) [2011-2016] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd." * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with * separate copyright notices and license terms. Your use of the source * code for these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. * */ package org.springframework.data.neo4j.conversion; import org.neo4j.ogm.MetaData; import org.neo4j.ogm.metadata.ClassInfo; import org.neo4j.ogm.metadata.FieldInfo; import org.neo4j.ogm.metadata.MethodInfo; import org.neo4j.ogm.typeconversion.AttributeConverter; import org.neo4j.ogm.typeconversion.ConversionCallback; import org.neo4j.ogm.typeconversion.ProxyAttributeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.convert.converter.Converter; import java.lang.reflect.ParameterizedType; /** * Specialisation of {@link GenericConversionService} that creates Spring-compatible converters from those known by the mapping * {@link MetaData}, allowing the OGM type converters to be reused throughout a Spring application. * * @author Adam George * @author Luanne Misquitta */ public class MetaDataDrivenConversionService extends GenericConversionService implements ConversionCallback { private static final Logger logger = LoggerFactory.getLogger(MetaDataDrivenConversionService.class); /** * Constructs a new {@link MetaDataDrivenConversionService} based on the given {@link MetaData}. * * @param metaData The OGM {@link MetaData} from which to elicit type converters configured in the underlying object-graph * mapping layer */ public MetaDataDrivenConversionService(MetaData metaData) { metaData.registerConversionCallback(this); for (ClassInfo classInfo : metaData.persistentEntities()) { for (FieldInfo fieldInfo : classInfo.propertyFields()) { if (fieldInfo.hasConverter()) { addWrappedConverter(fieldInfo.converter()); } } // TODO: do we need to check the setters too or are programmers obliged to annotate both? for (MethodInfo methodInfo : classInfo.propertyGetters()) { if (methodInfo.hasConverter()) { addWrappedConverter(methodInfo.converter()); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void addWrappedConverter(final AttributeConverter attributeConverter) { if (attributeConverter instanceof ProxyAttributeConverter) { return; } Converter<?, ?> toGraphConverter = new Converter() { @Override public Object convert(Object source) { return attributeConverter.toGraphProperty(source); } }; Converter<?, ?> toEntityConverter = new Converter() { @Override public Object convert(Object source) { return attributeConverter.toEntityAttribute(source); } }; ParameterizedType pt = (ParameterizedType) attributeConverter.getClass().getGenericInterfaces()[0]; Class<?> sourceType, targetType; if (pt.getActualTypeArguments()[0] instanceof Class) { sourceType = (Class<?>) pt.getActualTypeArguments()[0]; } else { //the argument may be a Collection for example sourceType = (Class<?>)((ParameterizedType) pt.getActualTypeArguments()[0]).getActualTypeArguments()[0]; } if (pt.getActualTypeArguments()[1] instanceof Class) { targetType = (Class<?>) pt.getActualTypeArguments()[1]; } else { targetType = (Class<?>)((ParameterizedType) pt.getActualTypeArguments()[1]).getActualTypeArguments()[1]; } if (canConvert(sourceType, targetType) && canConvert(targetType, sourceType)) { logger.info("Not adding Spring-compatible converter for " + attributeConverter.getClass() + " because one that does the same job has already been registered with the ConversionService."); } else { // It could be argued that this is wrong as it potentially overrides a registered converted that doesn't handle // both directions, but I've decided that it's better to ensure the same converter is used for load and save. addConverter(sourceType, targetType, toGraphConverter); addConverter(targetType, sourceType, toEntityConverter); } } @Override public <T> T convert(Class<T> targetType, Object value) { if (value == null) { return null; } return convert(value, targetType); } }
DATAGRAPH-873 - Fix MetaDataDrivenConversionService to compile against Spring Framework 4.3.
spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java
DATAGRAPH-873 - Fix MetaDataDrivenConversionService to compile against Spring Framework 4.3.
<ide><path>pring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java <ide> return; <ide> } <ide> <del> Converter<?, ?> toGraphConverter = new Converter() { <add> Converter toGraphConverter = new Converter() { <ide> @Override <ide> public Object convert(Object source) { <ide> return attributeConverter.toGraphProperty(source); <ide> } <ide> }; <del> Converter<?, ?> toEntityConverter = new Converter() { <add> Converter toEntityConverter = new Converter() { <ide> @Override <ide> public Object convert(Object source) { <ide> return attributeConverter.toEntityAttribute(source);
Java
apache-2.0
4ffa77d68fd0beb5f0736a7527f672cbcd63a74d
0
apache/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.appender.mom.jeromq; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.junit.LoggerContextRule; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; public class JeroMqAppenderTest { private static final String ENDPOINT = "tcp://localhost:5556"; private static final String APPENDER_NAME = "JeroMQAppender"; private static final int DEFAULT_TIMEOUT_MILLIS = 30000; @ClassRule public static LoggerContextRule ctx = new LoggerContextRule("JeroMqAppenderTest.xml"); @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testAppenderLifeCycle() throws Exception { // do nothing to make sure the appender starts and stops without // locking up resources. Assert.assertNotNull(JeroMqManager.getContext()); } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testClientServer() throws Exception { final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); final int expectedReceiveCount = 3; final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, expectedReceiveCount); final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future<List<String>> future = executor.submit(client); Thread.sleep(100); final Logger logger = ctx.getLogger(getClass().getName()); appender.resetSendRcs(); logger.info("Hello"); logger.info("Again"); ThreadContext.put("foo", "bar"); logger.info("World"); final List<String> list = future.get(); Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); Assert.assertEquals("Hello", list.get(0)); Assert.assertEquals("Again", list.get(1)); Assert.assertEquals("barWorld", list.get(2)); } finally { executor.shutdown(); } } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testMultiThreadedServer() throws Exception { final int nThreads = 10; final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); final int expectedReceiveCount = 2 * nThreads; final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, expectedReceiveCount); final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future<List<String>> future = executor.submit(client); Thread.sleep(100); final Logger logger = ctx.getLogger(getClass().getName()); appender.resetSendRcs(); final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < 10.; i++) { fixedThreadPool.submit(new Runnable() { @Override public void run() { logger.info("Hello"); logger.info("Again"); } }); } final List<String> list = future.get(); Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); int hello = 0; int again = 0; for (final String string : list) { switch (string) { case "Hello": hello++; break; case "Again": again++; break; default: Assert.fail("Unexpected message: " + string); } } Assert.assertEquals(nThreads, hello); Assert.assertEquals(nThreads, again); } finally { executor.shutdown(); } } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testServerOnly() throws Exception { final Logger logger = ctx.getLogger(getClass().getName()); final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); appender.resetSendRcs(); logger.info("Hello"); logger.info("Again"); Assert.assertEquals(2, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); } }
log4j-core/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.appender.mom.jeromq; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.junit.LoggerContextRule; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; public class JeroMqAppenderTest { private static final int DEFAULT_TIMEOUT_MILLIS = 30000; @ClassRule public static LoggerContextRule ctx = new LoggerContextRule("JeroMqAppenderTest.xml"); @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testAppenderLifeCycle() throws Exception { // do nothing to make sure the appender starts and stops without // locking up resources. Assert.assertNotNull(JeroMqManager.getContext()); } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testClientServer() throws Exception { final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); final int expectedReceiveCount = 3; final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), "tcp://localhost:5556", expectedReceiveCount); final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future<List<String>> future = executor.submit(client); Thread.sleep(100); final Logger logger = ctx.getLogger(getClass().getName()); appender.resetSendRcs(); logger.info("Hello"); logger.info("Again"); ThreadContext.put("foo", "bar"); logger.info("World"); final List<String> list = future.get(); Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); Assert.assertEquals("Hello", list.get(0)); Assert.assertEquals("Again", list.get(1)); Assert.assertEquals("barWorld", list.get(2)); } finally { executor.shutdown(); } } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testMultiThreadedServer() throws Exception { final int nThreads = 10; final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); final int expectedReceiveCount = 2 * nThreads; final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), "tcp://localhost:5556", expectedReceiveCount); final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future<List<String>> future = executor.submit(client); Thread.sleep(100); final Logger logger = ctx.getLogger(getClass().getName()); appender.resetSendRcs(); final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < 10.; i++) { fixedThreadPool.submit(new Runnable() { @Override public void run() { logger.info("Hello"); logger.info("Again"); } }); } final List<String> list = future.get(); Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); int hello = 0; int again = 0; for (final String string : list) { switch (string) { case "Hello": hello++; break; case "Again": again++; break; default: Assert.fail("Unexpected message: " + string); } } Assert.assertEquals(nThreads, hello); Assert.assertEquals(nThreads, again); } finally { executor.shutdown(); } } @Test(timeout = DEFAULT_TIMEOUT_MILLIS) public void testServerOnly() throws Exception { final Logger logger = ctx.getLogger(getClass().getName()); final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); appender.resetSendRcs(); logger.info("Hello"); logger.info("Again"); Assert.assertEquals(2, appender.getSendRcTrue()); Assert.assertEquals(0, appender.getSendRcFalse()); } }
Refactor common strings into constants.
log4j-core/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java
Refactor common strings into constants.
<ide><path>og4j-core/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java <ide> <ide> public class JeroMqAppenderTest { <ide> <add> private static final String ENDPOINT = "tcp://localhost:5556"; <add> <add> private static final String APPENDER_NAME = "JeroMQAppender"; <add> <ide> private static final int DEFAULT_TIMEOUT_MILLIS = 30000; <ide> <ide> @ClassRule <ide> <ide> @Test(timeout = DEFAULT_TIMEOUT_MILLIS) <ide> public void testClientServer() throws Exception { <del> final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); <add> final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); <ide> final int expectedReceiveCount = 3; <del> final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), "tcp://localhost:5556", expectedReceiveCount); <add> final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, expectedReceiveCount); <ide> final ExecutorService executor = Executors.newSingleThreadExecutor(); <ide> try { <ide> final Future<List<String>> future = executor.submit(client); <ide> @Test(timeout = DEFAULT_TIMEOUT_MILLIS) <ide> public void testMultiThreadedServer() throws Exception { <ide> final int nThreads = 10; <del> final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); <add> final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); <ide> final int expectedReceiveCount = 2 * nThreads; <del> final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), "tcp://localhost:5556", <add> final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, <ide> expectedReceiveCount); <ide> final ExecutorService executor = Executors.newSingleThreadExecutor(); <ide> try { <ide> @Test(timeout = DEFAULT_TIMEOUT_MILLIS) <ide> public void testServerOnly() throws Exception { <ide> final Logger logger = ctx.getLogger(getClass().getName()); <del> final JeroMqAppender appender = ctx.getRequiredAppender("JeroMQAppender", JeroMqAppender.class); <add> final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class); <ide> appender.resetSendRcs(); <ide> logger.info("Hello"); <ide> logger.info("Again");
Java
apache-2.0
ead1d570d0e649f841e2147ed412674e380916a9
0
bozimmerman/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Behaviors; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import org.mozilla.javascript.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.planet_ink.coffee_mud.Libraries.interfaces.*; /* Copyright 2000-2007 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Scriptable extends StdBehavior implements ScriptingEngine { public String ID(){return "Scriptable";} protected int canImproveCode(){return Behavior.CAN_MOBS|Behavior.CAN_ITEMS|Behavior.CAN_ROOMS;} protected MOB lastToHurtMe=null; protected Room lastKnownLocation=null; protected Tickable altStatusTickable=null; protected Vector que=new Vector(); protected static final Hashtable funcH=new Hashtable(); protected static final Hashtable methH=new Hashtable(); protected static final Hashtable progH=new Hashtable(); private static Hashtable patterns=new Hashtable(); protected Vector oncesDone=new Vector(); protected Hashtable delayTargetTimes=new Hashtable(); protected Hashtable delayProgCounters=new Hashtable(); protected Hashtable lastTimeProgsDone=new Hashtable(); protected Hashtable lastDayProgsDone=new Hashtable(); private HashSet registeredSpecialEvents=new HashSet(); private Hashtable noTrigger=new Hashtable(); protected long tickStatus=Tickable.STATUS_NOT; private Quest defaultQuest=null; protected CMMsg lastMsg=null; protected Environmental lastLoaded=null; protected static HashSet SIGNS=CMParms.makeHashSet(CMParms.parseCommas("==,>=,>,<,<=,=>,=<,!=",true)); private Quest getQuest(String named) { if((defaultQuest!=null)&&(named.equals("*")||named.equalsIgnoreCase(defaultQuest.name()))) return defaultQuest; Quest Q=null; for(int i=0;i<CMLib.quests().numQuests();i++) { try{Q=CMLib.quests().fetchQuest(i);}catch(Exception e){} if(Q!=null) { if(Q.name().equalsIgnoreCase(named)) if(Q.running()) return Q; } } return CMLib.quests().fetchQuest(named); } public long getTickStatus() { Tickable T=altStatusTickable; if(T!=null) return T.getTickStatus(); return tickStatus; } public void registerDefaultQuest(Quest Q){ defaultQuest=Q; } public boolean endQuest(Environmental hostObj, MOB mob, String quest) { if(mob!=null) { Vector scripts=getScripts(); if(!mob.amDead()) lastKnownLocation=mob.location(); for(int v=0;v<scripts.size();v++) { Vector script=(Vector)scripts.elementAt(v); String trigger=""; if(script.size()>0) trigger=((String)script.elementAt(0)).toUpperCase().trim(); if((getTriggerCode(trigger)==13) //questtimeprog &&(!oncesDone.contains(script)) &&(CMParms.getCleanBit(trigger,1).equalsIgnoreCase(quest)||(quest.equalsIgnoreCase("*"))) &&(CMath.s_int(CMParms.getCleanBit(trigger,2).trim())<0)) { oncesDone.addElement(script); execute(hostObj,mob,mob,mob,null,null,script,null,new Object[12]); return true; } } } return false; } public Vector externalFiles() { Vector xmlfiles=new Vector(); parseParmFilenames(getParms(),xmlfiles,0); return xmlfiles; } public String getVarHost(Environmental E, String rawHost, MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { if(!rawHost.equals("*")) { if(E==null) rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost); else if(E instanceof Room) rawHost=CMLib.map().getExtendedRoomID((Room)E); else rawHost=E.Name(); } return rawHost; } public String getVar(Environmental E, String rawHost, String var, MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var); } public static String getVar(String host, String var) { Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+host); String val=""; if(H!=null) { val=(String)H.get(var.toUpperCase()); if(val==null) val=""; } return val; } private StringBuffer getResourceFileData(String named) { if(getQuest("*")!=null) return getQuest("*").getResourceFileData(named); return new CMFile(Resources.makeFileResourceName(named),null,true).text(); } protected static class JScriptEvent extends ScriptableObject { public String getClassName(){ return "JScriptEvent";} static final long serialVersionUID=43; Environmental h=null; MOB s=null; Environmental t=null; MOB m=null; Item pi=null; Item si=null; Vector scr; String message=null; public Environmental host(){return h;} public MOB source(){return s;} public Environmental target(){return t;} public MOB monster(){return m;} public Item item(){return pi;} public Item item2(){return si;} public String message(){return message;} public void setVar(String host, String var, String value) { Scriptable.mpsetvar(host.toString(),var.toString().toUpperCase(),value.toString()); } public String getVar(String host, String var) { return Scriptable.getVar(host,var);} public String toJavaString(Object O){return Context.toString(O);} public JScriptEvent(Environmental host, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg) { h=host; s=source; t=target; m=monster; pi=primaryItem; si=secondaryItem; message=msg; } } public void setParms(String newParms) { newParms=CMStrings.replaceAll(newParms,"'","`"); if(newParms.startsWith("+")) { String superParms=super.getParms(); if(superParms.length()>100) Resources.removeResource("PARSEDPRG: "+superParms.substring(0,100)+superParms.length()+superParms.hashCode()); else Resources.removeResource("PARSEDPRG: "+superParms); newParms=super.getParms()+";"+newParms.substring(1); } que=new Vector(); oncesDone=new Vector(); delayTargetTimes=new Hashtable(); delayProgCounters=new Hashtable(); lastTimeProgsDone=new Hashtable(); lastDayProgsDone=new Hashtable(); registeredSpecialEvents=new HashSet(); noTrigger=new Hashtable(); super.setParms(newParms); if(oncesDone.size()>0) oncesDone.clear(); } protected void parseParmFilenames(String parse, Vector filenames, int depth) { if(depth>10) return; // no including off to infinity while(parse.length()>0) { int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { if(parse.substring(0,y).trim().endsWith("#")) { parse=parse.substring(y+1); continue; } int z=parse.indexOf("~",y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf("~",z+1); if(z>0) { String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); filenames.addElement(filename); parseParmFilenames(getResourceFileData(filename).toString(),filenames,depth+1); } else { String filename=parse.substring(y+5).trim(); filenames.addElement(filename); parseParmFilenames(getResourceFileData(filename).toString(),filenames,depth+1); break; } } else break; } } protected String parseLoads(String text, int depth) { StringBuffer results=new StringBuffer(""); String parse=text; if(depth>10) return ""; // no including off to infinity String p=null; while(parse.length()>0) { int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { p=parse.substring(0,y).trim(); if((!p.endsWith(";")) &&(!p.endsWith("\n")) &&(!p.endsWith("\r")) &&(p.length()>0)) { results.append(parse.substring(0,y+1)); parse=parse.substring(y+1); continue; } results.append(p+"\n"); int z=parse.indexOf("~",y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf("~",z+1); if(z>0) { String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); results.append(parseLoads(getResourceFileData(filename).toString(),depth+1)); } else { String filename=parse.substring(y+5).trim(); results.append(parseLoads(getResourceFileData(filename).toString(),depth+1)); break; } } else { results.append(parse); break; } } return results.toString(); } protected Vector parseScripts(String text) { synchronized(funcH) { if(funcH.size()==0) { for(int i=0;i<funcs.length;i++) funcH.put(funcs[i],new Integer(i+1)); for(int i=0;i<methods.length;i++) methH.put(methods[i],new Integer(i+1)); for(int i=0;i<progs.length;i++) progH.put(progs[i],new Integer(i+1)); } } Vector V=new Vector(); text=parseLoads(text,0); int y=0; while((text!=null)&&(text.length()>0)) { y=text.indexOf("~"); while((y>0)&&(text.charAt(y-1)=='\\')) y=text.indexOf("~",y+1); String script=""; if(y<0) { script=text.trim(); text=""; } else { script=text.substring(0,y).trim(); text=text.substring(y+1).trim(); } if(script.length()>0) V.addElement(script); } for(int v=0;v<V.size();v++) { String s=(String)V.elementAt(v); Vector script=new Vector(); while(s.length()>0) { y=-1; int yy=0; while(yy<s.length()) if((s.charAt(yy)==';')&&((yy<=0)||(s.charAt(yy-1)!='\\'))) {y=yy;break;} else if(s.charAt(yy)=='\n'){y=yy;break;} else if(s.charAt(yy)=='\r'){y=yy;break;} else yy++; String cmd=""; if(y<0) { cmd=s.trim(); s=""; } else { cmd=s.substring(0,y).trim(); s=s.substring(y+1).trim(); } if((cmd.length()>0)&&(!cmd.startsWith("#"))) { cmd=CMStrings.replaceAll(cmd,"\\~","~"); cmd=CMStrings.replaceAll(cmd,"\\=","="); script.addElement(CMStrings.replaceAll(cmd,"\\;",";")); } } V.setElementAt(script,v); } V.trimToSize(); return V; } protected Room getRoom(String thisName, Room imHere) { if(thisName.length()==0) return null; Room room=CMLib.map().getRoom(thisName); if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName))) return room; Room inAreaRoom=null; try { for(Enumeration p=CMLib.map().players();p.hasMoreElements();) { MOB M=(MOB)p.nextElement(); if((M.Name().equalsIgnoreCase(thisName)) &&(M.location()!=null) &&(CMLib.flags().isInTheGame(M,true))) inAreaRoom=M.location(); } if(inAreaRoom==null) for(Enumeration p=CMLib.map().players();p.hasMoreElements();) { MOB M=(MOB)p.nextElement(); if((M.name().equalsIgnoreCase(thisName)) &&(M.location()!=null) &&(CMLib.flags().isInTheGame(M,true))) inAreaRoom=M.location(); } if(inAreaRoom==null) for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if((R.roomID().endsWith("#"+thisName)) ||(R.roomID().endsWith(thisName))) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if(CMLib.english().containsString(R.displayText(),thisName)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if(CMLib.english().containsString(R.description(),thisName)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if((R.fetchInhabitant(thisName)!=null) ||(R.fetchItem(null,thisName)!=null)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; return room; } protected void scriptableError(Environmental scripted, String cmdName, String errType, String errMsg) { if(scripted!=null) { Room R=CMLib.map().roomLocation(scripted); Log.errOut("Scriptable",scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg); if(R!=null) R.showHappens(CMMsg.MSG_OK_VISUAL,"Scriptable Error: "+scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+CMParms.toStringList(externalFiles())+"/"+ cmdName+"/"+errType+"/"+errMsg); } else Log.errOut("Scriptable","*/*/"+CMParms.toStringList(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg); } protected boolean simpleEvalStr(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { int x=arg1.compareToIgnoreCase(arg2); if(cmp.equalsIgnoreCase("==")) return (x==0); else if(cmp.equalsIgnoreCase(">=")) return (x==0)||(x>0); else if(cmp.equalsIgnoreCase("<=")) return (x==0)||(x<0); else if(cmp.equalsIgnoreCase(">")) return (x>0); else if(cmp.equalsIgnoreCase("<")) return (x<0); else if(cmp.equalsIgnoreCase("!=")) return (x!=0); else { scriptableError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2); return false; } } protected boolean simpleEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { long val1=CMath.s_long(arg1.trim()); long val2=CMath.s_long(arg2.trim()); if(cmp.equalsIgnoreCase("==")) return (val1==val2); else if(cmp.equalsIgnoreCase(">=")) return val1>=val2; else if(cmp.equalsIgnoreCase("<=")) return val1<=val2; else if(cmp.equalsIgnoreCase(">")) return (val1>val2); else if(cmp.equalsIgnoreCase("<")) return (val1<val2); else if(cmp.equalsIgnoreCase("!=")) return (val1!=val2); else { scriptableError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } } protected boolean simpleExpressionEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { double val1=CMath.s_parseMathExpression(arg1.trim()); double val2=CMath.s_parseMathExpression(arg2.trim()); if(cmp.equalsIgnoreCase("==")) return (val1==val2); else if(cmp.equalsIgnoreCase(">=")) return val1>=val2; else if(cmp.equalsIgnoreCase("<=")) return val1<=val2; else if(cmp.equalsIgnoreCase(">")) return (val1>val2); else if(cmp.equalsIgnoreCase("<")) return (val1<val2); else if(cmp.equalsIgnoreCase("!=")) return (val1!=val2); else { scriptableError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } } protected Vector loadMobsFromFile(Environmental scripted, String filename) { filename=filename.trim(); Vector monsters=(Vector)Resources.getResource("RANDOMMONSTERS-"+filename); if(monsters!=null) return monsters; StringBuffer buf=getResourceFileData(filename); String thangName="null"; Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { scriptableError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } if(buf.substring(0,20).indexOf("<MOBS>")<0) { scriptableError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } monsters=new Vector(); String error=CMLib.coffeeMaker().addMOBsFromXML(buf.toString(),monsters,null); if(error.length()>0) { scriptableError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(monsters.size()<=0) { scriptableError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMMONSTERS-"+filename,monsters); return monsters; } protected Vector loadItemsFromFile(Environmental scripted, String filename) { filename=filename.trim(); Vector items=(Vector)Resources.getResource("RANDOMITEMS-"+filename); if(items!=null) return items; StringBuffer buf=getResourceFileData(filename); String thangName="null"; Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { scriptableError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } if(buf.substring(0,20).indexOf("<ITEMS>")<0) { scriptableError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } items=new Vector(); String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null); if(error.length()>0) { scriptableError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(items.size()<=0) { scriptableError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMITEMS-"+filename,items); return items; } protected Environmental findSomethingCalledThis(String thisName, MOB meMOB, Room imHere, Vector OBJS, boolean mob) { if(thisName.length()==0) return null; Environmental thing=null; Environmental areaThing=null; ShopKeeper SK=null; if(thisName.toUpperCase().trim().startsWith("FROMFILE ")) { try{ Vector V=null; if(mob) V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1)); else V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1)); if(V!=null) { String name=CMParms.getPastBit(thisName,1); if(name.equalsIgnoreCase("ALL")) OBJS=V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=(Environmental)V.elementAt(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(Exception e){} } else { if(!mob) areaThing=(meMOB!=null)?meMOB.fetchInventory(thisName):null; try { if(areaThing==null) for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); Environmental E=null; if(mob) E=R.fetchInhabitant(thisName); else { E=R.fetchItem(null,thisName); if(E==null) for(int i=0;i<R.numInhabitants();i++) { MOB M=R.fetchInhabitant(i); if(M!=null) { E=M.fetchInventory(thisName); SK=CMLib.coffeeShops().getShopKeeper(M); if((SK!=null)&&(E==null)) E=SK.getShop().getStock(thisName,null,SK.whatIsSold(),M.getStartRoom()); } } } if(E!=null) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) areaThing=E; else thing=E; } } }catch(NoSuchElementException nse){} } if(areaThing!=null) OBJS.addElement(areaThing); else if(thing!=null) OBJS.addElement(thing); if(OBJS.size()>0) return (Environmental)OBJS.firstElement(); return null; } public Environmental getArgumentMOB(String str, MOB source, MOB monster, Environmental target, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); } public Environmental getArgumentItem(String str, MOB source, MOB monster, Environmental scripted, Environmental target, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { if(str.length()<2) return null; if(str.charAt(0)=='$') { if(Character.isDigit(str.charAt(1))) { Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))]; if(O instanceof Environmental) return (Environmental)O; else if((O instanceof Vector)&&(str.length()>3)&&(str.charAt(2)=='.')) { Vector V=(Vector)O; String back=str.substring(2); if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length())&&(Character.isDigit(back.charAt(x)))) x++; int y=CMath.s_int(back.substring(1,x).trim()); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) return null; O=V.elementAt(y); if(O instanceof Environmental) return (Environmental)O; } str=O.toString(); // will fall through } } else if(O!=null) str=O.toString(); // will fall through else return null; } else switch(str.charAt(1)) { case 'a': return (lastKnownLocation!=null)?lastKnownLocation.getArea():null; case 'B': case 'b': return lastLoaded; case 'N': case 'n': return source; case 'I': case 'i': return scripted; case 'T': case 't': return target; case 'O': case 'o': return primaryItem; case 'P': case 'p': return secondaryItem; case 'd': case 'D': return lastKnownLocation; case 'F': case 'f': if((monster!=null)&&(monster.amFollowing()!=null)) return monster.amFollowing(); return null; case 'r': case 'R': return getRandPC(monster,tmp,lastKnownLocation); case 'c': case 'C': return getRandAnyone(monster,tmp,lastKnownLocation); case 'w': return primaryItem!=null?primaryItem.owner():null; case 'W': return secondaryItem!=null?secondaryItem.owner():null; case 'x': case 'X': if(lastKnownLocation!=null) { if((str.length()>2)&&(Directions.getGoodDirectionCode(""+str.charAt(2))>=0)) return lastKnownLocation.getExitInDir(Directions.getGoodDirectionCode(""+str.charAt(2))); int i=0; Exit E=null; while(((++i)<100)||(E!=null)) E=lastKnownLocation.getExitInDir(CMLib.dice().roll(1,Directions.NUM_DIRECTIONS,-1)); return E; } return null; case '[': { int x=str.substring(2).indexOf("]"); if(x>=0) { String mid=str.substring(2).substring(0,x); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) return Q.getQuestItem(num); } } } break; case '{': { int x=str.substring(2).indexOf("}"); if(x>=0) { String mid=str.substring(2).substring(0,x).trim(); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) return Q.getQuestMob(num); } } } break; } } if(lastKnownLocation!=null) { str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str); Environmental E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str,Item.WORNREQ_ANY); if(E==null) E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Item.WORNREQ_ANY); if(E==null) E=lastKnownLocation.fetchAnyItem(str); if((E==null)&&(monster!=null)) E=monster.fetchInventory(str); return E; } return null; } private String makeNamedString(Object O) { if(O instanceof Vector) return makeParsableString((Vector)O); else if(O instanceof Room) return ((Room)O).roomTitle(); else if(O instanceof Environmental) return ((Environmental)O).Name(); else if(O!=null) return O.toString(); return ""; } private String makeParsableString(Vector V) { if((V==null)||(V.size()==0)) return ""; if(V.firstElement() instanceof String) return CMParms.combineWithQuotes(V,0); StringBuffer ret=new StringBuffer(""); String S=null; for(int v=0;v<V.size();v++) { S=makeNamedString(V.elementAt(v)).trim(); if(S.length()==0) ret.append("? "); else if(S.indexOf(" ")>=0) ret.append("\""+S+"\" "); else ret.append(S+" "); } return ret.toString(); } public String varify(MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String varifyable) { int t=varifyable.indexOf("$"); if((monster!=null)&&(monster.location()!=null)) lastKnownLocation=monster.location(); if(lastKnownLocation==null) lastKnownLocation=source.location(); MOB randMOB=null; while((t>=0)&&(t<varifyable.length()-1)) { char c=varifyable.charAt(t+1); String middle=""; String front=varifyable.substring(0,t); String back=varifyable.substring(t+2); if(Character.isDigit(c)) middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]); else switch(c) { case '@': if((t<varifyable.length()-2)&&Character.isLetter(varifyable.charAt(t+2))) { Environmental E=getArgumentItem("$"+varifyable.charAt(t+2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); middle=(E==null)?"null":""+E; } break; case 'a': if(lastKnownLocation!=null) middle=lastKnownLocation.getArea().name(); break; case 'b': middle=lastLoaded!=null?lastLoaded.name():""; break; case 'B': middle=lastLoaded!=null?lastLoaded.displayText():""; break; case 'c': case 'C': randMOB=getRandAnyone(monster,tmp,lastKnownLocation); if(randMOB!=null) middle=randMOB.name(); break; case 'i': if(monster!=null) middle=monster.name(); break; case 'I': if(monster!=null) middle=monster.displayText(); break; case 'n': case 'N': if(source!=null) middle=source.name(); break; case 't': case 'T': if(target!=null) middle=target.name(); break; case 'y': if(source!=null) middle=source.charStats().sirmadam(); break; case 'Y': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().sirmadam(); break; case 'r': case 'R': randMOB=getRandPC(monster,tmp,lastKnownLocation); if(randMOB!=null) middle=randMOB.name(); break; case 'j': if(monster!=null) middle=monster.charStats().heshe(); break; case 'f': if((monster!=null)&&(monster.amFollowing()!=null)) middle=monster.amFollowing().name(); break; case 'F': if((monster!=null)&&(monster.amFollowing()!=null)) middle=monster.amFollowing().charStats().heshe(); break; case 'e': if(source!=null) middle=source.charStats().heshe(); break; case 'E': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().heshe(); break; case 'J': randMOB=getRandPC(monster,tmp,lastKnownLocation); if(randMOB!=null) middle=randMOB.charStats().heshe(); break; case 'k': if(monster!=null) middle=monster.charStats().hisher(); break; case 'm': if(source!=null) middle=source.charStats().hisher(); break; case 'M': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().hisher(); break; case 'K': randMOB=getRandPC(monster,tmp,lastKnownLocation); if(randMOB!=null) middle=randMOB.charStats().hisher(); break; case 'o': case 'O': if(primaryItem!=null) middle=primaryItem.name(); break; case 'g': middle=((msg==null)?"":msg.toLowerCase()); break; case 'G': middle=((msg==null)?"":msg); break; case 'd': middle=(lastKnownLocation!=null)?lastKnownLocation.roomTitle():""; break; case 'D': middle=(lastKnownLocation!=null)?lastKnownLocation.roomDescription():""; break; case 'p': case 'P': if(secondaryItem!=null) middle=secondaryItem.name(); break; case 'w': middle=primaryItem!=null?primaryItem.owner().Name():middle; break; case 'W': middle=secondaryItem!=null?secondaryItem.owner().Name():middle; break; case 'l': if(lastKnownLocation!=null) { StringBuffer str=new StringBuffer(""); for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if((M!=null)&&(M!=monster)&&(CMLib.flags().canBeSeenBy(M,monster))) str.append("\""+M.name()+"\" "); } middle=str.toString(); } break; case 'L': if(lastKnownLocation!=null) { StringBuffer str=new StringBuffer(""); for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)&&(CMLib.flags().canBeSeenBy(I,monster))) str.append("\""+I.name()+"\" "); } middle=str.toString(); } break; case '<': { int x=back.indexOf(">"); if(x>=0) { String mid=back.substring(0,x); int y=mid.indexOf(" "); Environmental E=null; String arg1=""; if(y>=0) { arg1=mid.substring(0,y).trim(); E=getArgumentItem(arg1,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); mid=mid.substring(y+1).trim(); } if(arg1.length()>0) middle=getVar(E,arg1,mid,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); back=back.substring(x+1); } } break; case '[': { middle=""; int x=back.indexOf("]"); if(x>=0) { String mid=back.substring(0,x); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) middle=Q.getQuestItemName(num); } back=back.substring(x+1); } } break; case '{': { middle=""; int x=back.indexOf("}"); if(x>=0) { String mid=back.substring(0,x).trim(); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) middle=Q.getQuestMobName(num); } back=back.substring(x+1); } } break; case '%': { middle=""; int x=back.indexOf("%"); if(x>=0) { middle=functify(monster,source,target,monster,primaryItem,secondaryItem,msg,tmp,back.substring(0,x).trim()); back=back.substring(x+1); } } break; //case 'a': case 'A': // unnecessary, since, in coffeemud, this is part of the name break; case 'x': case 'X': if(lastKnownLocation!=null) { middle=""; Exit E=null; int dir=-1; if((t<varifyable.length()-2)&&(Directions.getGoodDirectionCode(""+varifyable.charAt(t+2))>=0)) { dir=Directions.getGoodDirectionCode(""+varifyable.charAt(t+2)); E=lastKnownLocation.getExitInDir(dir); } else { int i=0; while(((++i)<100)||(E!=null)) { dir=CMLib.dice().roll(1,Directions.NUM_DIRECTIONS,-1); E=lastKnownLocation.getExitInDir(dir); } } if((dir>=0)&&(E!=null)) { if(c=='x') middle=Directions.getDirectionName(dir); else middle=E.name(); } } break; } if((middle.length()>0) &&(back.startsWith(".")) &&(back.length()>1)) { if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if(back.equalsIgnoreCase("#LENGTH#")) middle=""+CMParms.parse(middle).size(); else if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length()) &&(Character.isDigit(back.charAt(x)))) x++; int y=CMath.s_int(back.substring(1,x).trim()); back=back.substring(x); boolean rest=back.startsWith(".."); if(rest) back=back.substring(2); Vector V=CMParms.parse(middle); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) middle=""; else if(rest) middle=CMParms.combine(V,y); else middle=(String)V.elementAt(y); } } } varifyable=front+middle+back; t=varifyable.indexOf("$"); } return varifyable; } public static DVector getScriptVarSet(String mobname, String varname) { DVector set=new DVector(2); if(mobname.equals("*")) { Vector V=Resources.findResourceKeys("SCRIPTVAR-"); for(int v=0;v<V.size();v++) { String key=(String)V.elementAt(v); if(key.startsWith("SCRIPTVAR-")) { Hashtable H=(Hashtable)Resources.getResource(key); if(varname.equals("*")) { for(Enumeration e=H.keys();e.hasMoreElements();) { String vn=(String)e.nextElement(); set.addElement(key.substring(10),vn); } } else set.addElement(key.substring(10),varname); } } } else { Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+mobname); if(varname.equals("*")) { for(Enumeration e=H.keys();e.hasMoreElements();) { String vn=(String)e.nextElement(); set.addElement(mobname,vn); } } else set.addElement(mobname,varname); } return set; } public String getStatValue(Environmental E, String arg2) { boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if((!found)&&(E instanceof MOB)) { MOB M=(MOB)E; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.STAT_DESCS[i]); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } if(!found) for(int i=0;i<M.envStats().getStatCodes().length;i++) if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.envStats().getStat(M.envStats().getStatCodes()[i]); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } if(!found)return null; return val; } public String getGStatValue(Environmental E, String arg2) { if(E==null) return null; boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if(!found) if(E instanceof MOB) { for(int i=0;i<CMObjectBuilder.GENMOBCODES.length;i++) { if(CMObjectBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2)) { val=CMLib.coffeeMaker().getGenMobStat((MOB)E,CMObjectBuilder.GENMOBCODES[i]); found=true; break; } } if(!found) { MOB M=(MOB)E; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.STAT_DESCS[i]); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } if(!found) for(int i=0;i<M.envStats().getStatCodes().length;i++) if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.envStats().getStat(M.envStats().getStatCodes()[i]); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } } else if(E instanceof Item) { for(int i=0;i<CMObjectBuilder.GENITEMCODES.length;i++) { if(CMObjectBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2)) { val=CMLib.coffeeMaker().getGenItemStat((Item)E,CMObjectBuilder.GENITEMCODES[i]); found=true; break; } } } if(found) return val; return null; } public static void mpsetvar(String name, String key, String val) { DVector V=getScriptVarSet(name,key); for(int v=0;v<V.size();v++) { name=(String)V.elementAt(v,1); key=((String)V.elementAt(v,2)).toUpperCase(); Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+name); if(H==null) { if(val.length()==0) continue; H=new Hashtable(); Resources.submitResource("SCRIPTVAR-"+name,H); } if(val.equals("++")) { String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())+1).toString(); } else if(val.equals("--")) { String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())-1).toString(); } else if(val.startsWith("+")) { // add via +number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())+amount).toString(); } else if(val.startsWith("-")) { // subtract -number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())-amount).toString(); } else if(val.startsWith("*")) { // multiply via *number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())*amount).toString(); } else if(val.startsWith("/")) { // divide /number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())/amount).toString(); } if(H.containsKey(key)) H.remove(key); if(val.trim().length()>0) H.put(key,val); if(H.size()==0) Resources.removeResource("SCRIPTVAR-"+name); } } public boolean eval(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String evaluable) { boolean anythingChanged=false; Vector formatCheck=CMParms.parse(evaluable); for(int i=1;i<(formatCheck.size()-1);i++) if((SIGNS.contains(formatCheck.elementAt(i))) &&(((String)formatCheck.elementAt(i-1)).endsWith(")"))) { anythingChanged=true; String ps=(String)formatCheck.elementAt(i-1); ps=ps.substring(0,ps.length()-1); if(ps.length()==0) ps=" "; formatCheck.setElementAt(ps,i-1); String os=null; if((((String)formatCheck.elementAt(i+1)).startsWith("'") ||((String)formatCheck.elementAt(i+1)).startsWith("`"))) { os=""; while((i<(formatCheck.size()-1)) &&((!((String)formatCheck.elementAt(i+1)).endsWith("'")) &&(!((String)formatCheck.elementAt(i+1)).endsWith("`")))) { os+=((String)formatCheck.elementAt(i+1))+" "; formatCheck.removeElementAt(i+1); } os=(os+((String)formatCheck.elementAt(i+1))).trim(); } else if((i==(formatCheck.size()-3)) &&(((String)formatCheck.lastElement()).indexOf("(")<0)) { os=((String)formatCheck.elementAt(i+1)) +" "+((String)formatCheck.elementAt(i+2)); formatCheck.removeElementAt(i+2); } else os=(String)formatCheck.elementAt(i+1); os=os+")"; formatCheck.setElementAt(os,i+1); i+=2; } if(anythingChanged) evaluable=CMParms.combine(formatCheck,0); String uevaluable=evaluable.toUpperCase().trim(); boolean returnable=false; boolean lastreturnable=true; int joined=0; while(evaluable.length()>0) { int y=evaluable.indexOf("("); int z=y+1; int numy=1; while((y>=0)&&(numy>0)&&(z<evaluable.length())) { if(evaluable.charAt(z)=='(') numy++; else if(evaluable.charAt(z)==')') numy--; z++; } if((y<0)||(numy>0)||(z<=y)) { scriptableError(scripted,"EVAL","Format",evaluable); return false; } z--; String preFab=uevaluable.substring(0,y).trim(); Integer funcCode=(Integer)funcH.get(preFab); if(funcCode==null) funcCode=new Integer(0); if(y==0) { int depth=0; int i=0; while((++i)<evaluable.length()) { char c=evaluable.charAt(i); if((c==')')&&(depth==0)) { String expr=evaluable.substring(1,i); evaluable=evaluable.substring(i+1).trim(); uevaluable=uevaluable.substring(i+1).trim(); returnable=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,expr); switch(joined) { case 1: returnable=lastreturnable&&returnable; break; case 2: returnable=lastreturnable||returnable; break; case 4: returnable=!returnable; break; case 5: returnable=lastreturnable&&(!returnable); break; case 6: returnable=lastreturnable||(!returnable); break; default: break; } joined=0; break; } else if(c=='(') depth++; else if(c==')') depth--; } z=evaluable.indexOf(")"); } else if(evaluable.startsWith("!")) { joined=joined|4; evaluable=evaluable.substring(1).trim(); uevaluable=uevaluable.substring(1).trim(); } else if(uevaluable.startsWith("AND ")) { joined=1; lastreturnable=returnable; evaluable=evaluable.substring(4).trim(); uevaluable=uevaluable.substring(4).trim(); } else if(uevaluable.startsWith("OR ")) { joined=2; lastreturnable=returnable; evaluable=evaluable.substring(3).trim(); uevaluable=uevaluable.substring(3).trim(); } else if((y<0)||(z<y)) { scriptableError(scripted,"()","Syntax",evaluable); break; } else { tickStatus=Tickable.STATUS_MISC+funcCode.intValue(); switch(funcCode.intValue()) { case 1: // rand { String num=evaluable.substring(y+1,z).trim(); if(num.endsWith("%")) num=num.substring(0,num.length()-1); int arg=CMath.s_int(num); if(CMLib.dice().rollPercentage()<arg) returnable=true; else returnable=false; break; } case 2: // has { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HAS","Syntax",evaluable); return returnable; } Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(E2!=null) returnable=((MOB)E).isMine(E2); else returnable=(((MOB)E).fetchInventory(arg2)!=null); } else if(E instanceof Item) returnable=CMLib.english().containsString(E.name(),arg2); else if(E instanceof Room) { if(E2 instanceof Item) returnable=((Room)E).isContent((Item)E2); else returnable=(((Room)E).fetchItem(null,arg2)!=null); } else returnable=false; break; } case 74: // hasnum { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((value.length()==0)||(item.length()==0)||(cmp.length()==0)) { scriptableError(scripted,"HASNUM","Syntax",evaluable); return returnable; } Item I=null; int num=0; if(E==null) returnable=false; else if(E instanceof MOB) { MOB M=(MOB)E; for(int i=0;i<M.inventorySize();i++) { I=M.fetchInventory(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Room) { Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.fetchItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else returnable=false; break; } case 67: // hastitle { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HASTITLE","Syntax",evaluable); return returnable; } if(E instanceof MOB) { MOB M=(MOB)E; returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2)); } else returnable=false; break; } case 3: // worn { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"WORN","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else if(E instanceof MOB) returnable=(((MOB)E).fetchWornItem(arg2)!=null); else if(E instanceof Item) returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Item.IN_INVENTORY))); else returnable=false; break; } case 4: // isnpc { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isMonster(); break; } case 87: // isbirthday { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else { MOB mob=(MOB)E; if(mob.playerStats()==null) returnable=false; else { int tage=mob.baseCharStats().getMyRace().getAgingChart()[Race.AGE_YOUNGADULT] +CMClass.globalClock().getYear() -mob.playerStats().getBirthday()[2]; int month=CMClass.globalClock().getMonth(); int day=CMClass.globalClock().getDayOfMonth(); int bday=mob.playerStats().getBirthday()[0]; int bmonth=mob.playerStats().getBirthday()[1]; if((tage>mob.baseCharStats().getStat(CharStats.STAT_AGE)) &&((month==bmonth)&&(day==bday))) returnable=true; else returnable=false; } } break; } case 5: // ispc { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=!((MOB)E).isMonster(); break; } case 6: // isgood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isGood(E); break; } case 8: // isevil { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isEvil(E); break; } case 9: // isneutral { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isNeutral(E); break; } case 54: // isalive { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) returnable=true; else returnable=false; break; } case 58: // isable { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) returnable=((MOB)E).fetchExpertise(X.ID())!=null; else returnable=((MOB)E).findAbility(arg2)!=null; } else returnable=false; break; } case 59: // isopen { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } break; } case 60: // islocked { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isLocked(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isLocked(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isLocked(); } break; } case 10: // isfight { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isInCombat(); break; } case 11: // isimmort { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,"IMMORT"); break; } case 12: // ischarmed { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0; break; } case 15: // isfollow { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).amFollowing()==null) returnable=false; else if(((MOB)E).amFollowing().location()!=lastKnownLocation) returnable=false; else returnable=true; break; } case 73: // isservant { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0)) returnable=false; else if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null) returnable=false; else returnable=true; break; } case 55: // ispkill { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL)) returnable=true; else returnable=false; break; } case 7: // isname { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.english().containsString(E.name(),arg2); break; } case 56: // name { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME"); break; } case 75: // currency { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY"); break; } case 61: // strin { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Vector V=CMParms.parse(arg1.toUpperCase()); returnable=V.contains(arg2.toUpperCase()); break; } case 62: // callfunc { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); String found=null; boolean validFunc=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) scriptableError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else returnable=!(found.trim().length()==0); break; } case 14: // affected { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=(E.fetchEffect(arg2)!=null); break; } case 69: // isbehave { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=(E.fetchBehavior(arg2)!=null); break; } case 70: // ipaddress { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster())) returnable=false; else returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS"); break; } case 28: // questwinner { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { if(E!=null) arg1=E.Name(); returnable=Q.wasWinner(arg1); } break; } case 29: // questmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.wasQuestMob(arg1)>=0); break; } case 31: // isquestmobalive { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.wasQuestMob(arg1)); if(M==null) returnable=false; else returnable=!M.amDead(); } break; } case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Vector MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA"); break; } case 33: // nummobs { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Vector MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } }catch(NoSuchElementException nse){} returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS"); break; } case 34: // numracesinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Room R=null; MOB M=null; for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA"); break; } case 35: // numraces { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } }catch(NoSuchElementException nse){} returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES"); break; } case 30: // questobj { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.wasQuestItem(arg1)>=0); break; } case 85: // islike { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.masking().maskCheck(arg2, E,false); break; } case 86: // strcontains { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); returnable=CMParms.stringContains(arg1,arg2)>=0; break; } case 92: // isodd { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } returnable = isodd; break; } case 16: // hitprcnt { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"HITPRCNT","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); int val1=(int)Math.round(hitPctD*100.0); returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT"); } break; } case 50: // isseason { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) for(int a=0;a<TimeClock.SEASON_DESCS.length;a++) if((TimeClock.SEASON_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getSeasonCode()==a)) {returnable=true; break;} break; } case 51: // isweather { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) for(int a=0;a<Climate.WEATHER_DESCS.length;a++) if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a)) {returnable=true; break;} break; } case 57: // ismoon { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) { if(arg1.length()==0) returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location()); else for(int a=0;a<TimeClock.PHASE_DESC.length;a++) if((TimeClock.PHASE_DESC[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getMoonPhase()==a)) { returnable=true; break; } } break; } case 38: // istime { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(monster.location()==null) returnable=false; else if(("daytime").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAY)) returnable=true; else if(("dawn").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAWN)) returnable=true; else if(("dusk").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DUSK)) returnable=true; else if(("nighttime").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_NIGHT)) returnable=true; else if((monster.location().getArea().getTimeObj().getTODCode()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 39: // isday { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 45: // nummobsroom { int num=0; int startbit=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); if((CMParms.numBits(evaluable.substring(y+1,z))>2) &&(!CMath.isInteger(CMParms.getCleanBit(evaluable.substring(y+1,z),1).trim()))) { String name=CMParms.getCleanBit(evaluable.substring(y+1,z),0); startbit++; if(!name.equalsIgnoreCase("*")) { num=0; Vector MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } } String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),startbit)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),startbit)); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMMOBSROOM"); break; } case 63: // numpcsroom { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+lastKnownLocation.numPCInhabitants(),arg2,arg1,"NUMPCSROOM"); break; } case 79: // numpcsarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if(lastKnownLocation!=null) { int num=0; for(int s=0;s<CMLib.sessions().size();s++) { Session S=CMLib.sessions().elementAt(s); if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA"); } break; } case 77: // explored { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),2)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) { scriptableError(scripted,"EXPLORED","Unknown Code",whom); return returnable; } Area A=null; if(!where.equalsIgnoreCase("world")) { Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 instanceof Area) A=(Area)E2; else A=CMLib.map().getArea(where); if(A==null) { scriptableError(scripted,"EXPLORED","Unknown Area",where); return returnable; } } if(lastKnownLocation!=null) { int pct=0; MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED"); } break; } case 72: // faction { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),2)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),3)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Faction F=CMLib.factions().getFaction(arg1); if((E==null)||(!(E instanceof MOB))) { scriptableError(scripted,"FACTION","Unknown Code",whom); return returnable; } if(F==null) { scriptableError(scripted,"FACTION","Unknown Faction",arg1); return returnable; } MOB M=(MOB)E; String value=null; if(!M.hasFaction(F.factionID())) value=""; else { int myfac=M.fetchFaction(F.factionID()); if(CMath.isNumber(arg2.trim())) value=new Integer(myfac).toString(); else { Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),myfac); if(FR==null) value=""; else value=FR.name(); } } if(lastKnownLocation!=null) returnable=simpleEval(scripted,value,arg2,cmp,"FACTION"); break; } case 46: // numitemsroom { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) ct++; } returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM"); break; } case 47: //mobitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); Item which=null; int ct=1; if(M!=null) for(int i=0;i<M.inventorySize();i++) { Item I=M.fetchInventory(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which=I; break;} ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); break; } case 49: // hastattoo { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HASTATTOO","Syntax",evaluable); break; } else if((E!=null)&&(E instanceof MOB)) returnable=(((MOB)E).fetchTattoo(arg2)!=null); else returnable=false; break; } case 48: // numitemsmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); MOB which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); int ct=1; if(which!=null) for(int i=0;i<which.inventorySize();i++) { Item I=which.fetchInventory(i); if((I!=null)&&(I.container()==null)) ct++; } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB"); break; } case 43: // roommob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 44: // roomitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which=I; break;} ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 36: // ishere { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(lastKnownLocation!=null) returnable=((lastKnownLocation.fetchAnyItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null)); else returnable=false; break; } case 17: // inroom { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"INROOM","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM"); } break; } case 90: // inarea { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"INAREA","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA"); } break; } case 89: // isrecall { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"ISRECALL","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().getStartRoom(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL"); } break; } case 37: // inlocale { String parms=evaluable.substring(y+1,z); String arg2=null; Environmental E=monster; if(CMParms.numBits(parms)==1) arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(parms)); else { E=getArgumentItem(CMParms.getCleanBit(parms,0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(parms,0)); } if(E==null) returnable=false; else if(arg2.length()==0) returnable=true; else { Room R=CMLib.map().roomLocation(E); if(R==null) returnable=false; else if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0) returnable=true; else returnable=false; } break; } case 18: // sex { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0).toUpperCase()); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase(); if(CMath.isNumber(arg3.trim())) switch(CMath.s_int(arg3.trim())) { case 0: arg3="NEUTER"; break; case 1: arg3="MALE"; break; case 2: arg3="FEMALE"; break; } Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"SEX","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase(); if(arg2.equals("==")) returnable=arg3.startsWith(sex); else if(arg2.equals("!=")) returnable=!arg3.startsWith(sex); else { scriptableError(scripted,"SEX","Syntax",evaluable); return returnable; } } break; } case 91: // datetime { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) scriptableError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { String val=null; switch(index) { case 2: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 3: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 4: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getMonth(); break; case 5: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getYear(); break; default: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay(); break; } returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME"); } break; } case 13: // stat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"STAT","Syntax",evaluable); break; } if(E==null) returnable=false; else { String val=getStatValue(E,arg2); if(val==null) { scriptableError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"STAT"); } break; } case 52: // gstat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"GSTAT","Syntax",evaluable); break; } if(E==null) returnable=false; else { String val=getGStatValue(E,arg2); if(val==null) { scriptableError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT"); } break; } case 19: // position { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase(); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"POSITION","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex="STANDING"; if(CMLib.flags().isSleeping(E)) sex="SLEEPING"; else if(CMLib.flags().isSitting(E)) sex="SITTING"; if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"POSITION","Syntax",evaluable); return returnable; } } break; } case 20: // level { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"LEVEL","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { int val1=E.envStats().level(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL"); } break; } case 80: // questpoints { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"QUESTPOINTS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getQuestPoint(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS"); } break; } case 83: // qvar { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Quest Q=getQuest(arg1); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"QVAR","Syntax",evaluable); return returnable; } if(Q==null) returnable=false; else returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR"); break; } case 84: // math { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); if(!CMath.isMathExpression(arg1)) { scriptableError(scripted,"MATH","Syntax",evaluable); return returnable; } if(!CMath.isMathExpression(arg3)) { scriptableError(scripted,"MATH","Syntax",evaluable); return returnable; } returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH"); break; } case 81: // trains { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"TRAINS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getTrains(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS"); } break; } case 82: // pracs { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"PRACS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getPractices(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS"); } break; } case 66: // clanrank { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLANRANK","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { int val1=(E instanceof MOB)?((MOB)E).getClanRole():-1; returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK"); } break; } case 64: // deity { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"DEITY","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).getWorshipCharID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"DEITY","Syntax",evaluable); return returnable; } } break; } case 68: // clandata { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLANDATA","Syntax",evaluable); return returnable; } String clanID=null; if((E!=null)&&(E instanceof MOB)) clanID=((MOB)E).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); Clan C=CMLib.clans().findClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(arg2.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} String whichVal=""; switch(whichVar) { case 0: whichVal=C.getAcceptanceSettings(); break; case 1: whichVal=C.getDetail(monster); break; case 2: whichVal=C.getDonation(); break; case 3: whichVal=""+C.getExp(); break; case 4: whichVal=Clan.GVT_DESCS[C.getGovernment()]; break; case 5: whichVal=C.getMorgue(); break; case 6: whichVal=C.getPolitics(); break; case 7: whichVal=C.getPremise(); break; case 8: whichVal=C.getRecall(); break; case 9: whichVal=""+C.getSize(); break; // size case 10: whichVal=Clan.CLANSTATUS_DESC[C.getStatus()]; break; case 11: whichVal=""+C.getTaxes(); break; case 12: whichVal=""+C.getTrophies(); break; case 13: whichVal=""+C.getType(); break; // type case 14: { Vector areas=C.getControlledAreas(); StringBuffer list=new StringBuffer(""); for(int i=0;i<areas.size();i++) list.append("\""+((Environmental)areas.elementAt(i)).name()+"\" "); whichVal=list.toString().trim(); break; // areas } case 15: { DVector members=C.getMemberList(); StringBuffer list=new StringBuffer(""); for(int i=0;i<members.size();i++) list.append("\""+((String)members.elementAt(i,1))+"\" "); whichVal=list.toString().trim(); break; // memberlist } case 16: MOB M=C.getResponsibleMember(); if(M!=null) whichVal=M.Name(); break; // topmember default: scriptableError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); break; } if(CMath.isNumber(whichVal.trim())&&CMath.isNumber(arg4.trim())) returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA"); else returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA"); } break; } case 65: // clan { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"CLAN","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).getClanID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"CLAN","Syntax",evaluable); return returnable; } } break; } case 88: // mood { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"MOOD","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else if(E.fetchEffect("Mood")!=null) { String sex=E.fetchEffect("Mood").text(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"MOOD","Syntax",evaluable); return returnable; } } break; } case 21: // class { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().displayClassName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } } break; } case 22: // baseclass { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } } break; } case 23: // race { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"RACE","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().raceName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"RACE","Syntax",evaluable); return returnable; } } break; } case 24: //racecat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"RACECAT","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"RACECAT","Syntax",evaluable); return returnable; } } break; } case 25: // goldamt { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return returnable; } returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT"); } break; } case 78: // exp { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"EXP","Syntax",evaluable); break; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getExperience(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP"); } break; } case 76: // value { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0)) { scriptableError(scripted,"VALUE","Syntax",evaluable); break; } if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { scriptableError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase())); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"VALUE","Syntax",evaluable); return returnable; } returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT"); } break; } case 26: // objtype { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"OBJTYPE","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { String sex=CMClass.classID(E).toUpperCase(); if(arg2.equals("==")) returnable=sex.indexOf(arg3)>=0; else if(arg2.equals("!=")) returnable=sex.indexOf(arg3)<0; else { scriptableError(scripted,"OBJTYPE","Syntax",evaluable); return returnable; } } break; } case 27: // var { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1).toUpperCase(); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"VAR","Syntax",evaluable); return returnable; } String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { scriptableError(scripted,"VAR","Syntax",evaluable); return returnable; } break; } case 41: // eval { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); if(arg3.length()==0) { scriptableError(scripted,"EVAL","Syntax",evaluable); return returnable; } if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { scriptableError(scripted,"EVAL","Syntax",evaluable); return returnable; } break; } case 40: // number { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) if(!Character.isDigit(val.charAt(i))) { isnumber=false; break;} returnable=isnumber; break; } case 42: // randnum { String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s.trim())) arg1=CMath.s_parseIntExpression(arg1s.trim()); else arg1=CMParms.parse(arg1s.trim()).size(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)).trim(); int arg3=0; if(CMath.isMathExpression(arg3s.trim())) arg3=CMath.s_parseIntExpression(arg3s.trim()); else arg3=CMParms.parse(arg3s.trim()).size(); arg3=CMLib.dice().roll(1,arg3,0); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM"); break; } case 71: // rand0num { String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s)) arg1=CMath.s_parseIntExpression(arg1s); else arg1=CMParms.parse(arg1s).size(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)).trim(); int arg3=0; if(CMath.isMathExpression(arg3s)) arg3=CMath.s_parseIntExpression(arg3s); else arg3=CMParms.parse(arg3s).size(); arg3=CMLib.dice().roll(1,arg3,-1); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM"); break; } case 53: // incontainer { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(arg2.length()==0) returnable=(((MOB)E).riding()==null); else if(E2!=null) returnable=(((MOB)E).riding()==E2); else returnable=false; } else if(E instanceof Item) { if(arg2.length()==0) returnable=(((Item)E).container()==null); else if(E2!=null) returnable=(((Item)E).container()==E2); else returnable=false; } else returnable=false; break; } default: scriptableError(scripted,"Unknown Eval",preFab,evaluable); return returnable; } if((z>=0)&&(z<=evaluable.length())) { evaluable=evaluable.substring(z+1).trim(); uevaluable=uevaluable.substring(z+1).trim(); } switch(joined) { case 1: returnable=lastreturnable&&returnable; break; case 2: returnable=lastreturnable||returnable; break; case 4: returnable=!returnable; break; case 5: returnable=lastreturnable&&(!returnable); break; case 6: returnable=lastreturnable||(!returnable); break; default: break; } joined=0; } } return returnable; } public String functify(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String evaluable) { String uevaluable=evaluable.toUpperCase().trim(); StringBuffer results = new StringBuffer(""); while(evaluable.length()>0) { int y=evaluable.indexOf("("); int z=evaluable.indexOf(")"); String preFab=(y>=0)?uevaluable.substring(0,y).trim():""; Integer funcCode=(Integer)funcH.get(preFab); if(funcCode==null) funcCode=new Integer(0); if(y==0) { int depth=0; int i=0; while((++i)<evaluable.length()) { char c=evaluable.charAt(i); if((c==')')&&(depth==0)) { String expr=evaluable.substring(1,i); evaluable=evaluable.substring(i+1); uevaluable=uevaluable.substring(i+1); results.append(functify(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,expr)); break; } else if(c=='(') depth++; else if(c==')') depth--; } z=evaluable.indexOf(")"); } else if((y<0)||(z<y)) { scriptableError(scripted,"()","Syntax",evaluable); break; } else { tickStatus=Tickable.STATUS_MISC2+funcCode.intValue(); switch(funcCode.intValue()) { case 1: // rand { results.append(CMLib.dice().rollPercentage()); break; } case 2: // has { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Vector choices=new Vector(); if(E==null) choices=new Vector(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).inventorySize();i++) { Item I=((MOB)E).fetchInventory(i); if((I!=null)&&(I.amWearingAt(Item.IN_INVENTORY))&&(I.container()==null)) choices.addElement(I); } } else if(E instanceof Item) { choices.addElement(E); if(E instanceof Container) choices=((Container)E).getContents(); } else if(E instanceof Room) { for(int i=0;i<((Room)E).numItems();i++) { Item I=((Room)E).fetchItem(i); if((I!=null)&&(I.container()==null)) choices.addElement(I); } } if(choices.size()>0) results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name()); break; } case 74: // hasnum { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((item.length()==0)||(E==null)) scriptableError(scripted,"HASNUM","Syntax",evaluable); else { Item I=null; int num=0; if(E instanceof MOB) { MOB M=(MOB)E; for(int i=0;i<M.inventorySize();i++) { I=M.fetchInventory(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; results.append(""+num); } else if(E instanceof Room) { Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.fetchItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } } break; } case 3: // worn { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Vector choices=new Vector(); if(E==null) choices=new Vector(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).inventorySize();i++) { Item I=((MOB)E).fetchInventory(i); if((I!=null)&&(!I.amWearingAt(Item.IN_INVENTORY))&&(I.container()==null)) choices.addElement(I); } } else if((E instanceof Item)&&(!(((Item)E).amWearingAt(Item.IN_INVENTORY)))) { choices.addElement(E); if(E instanceof Container) choices=((Container)E).getContents(); } if(choices.size()>0) results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name()); break; } case 4: // isnpc case 5: // ispc results.append("[unimplemented function]"); break; case 87: // isbirthday { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null)) { MOB mob=(MOB)E; TimeClock C=CMClass.globalClock(); int day=C.getDayOfMonth(); int month=C.getMonth(); int year=C.getYear(); int bday=mob.playerStats().getBirthday()[0]; int bmonth=mob.playerStats().getBirthday()[1]; if((month>bmonth)||((month==bmonth)&&(day>bday))) year++; StringBuffer timeDesc=new StringBuffer(""); if(C.getDaysInWeek()>0) { long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth(); x=x+((long)(bmonth-1))*((long)C.getDaysInMonth()); x=x+bmonth; timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", "); } timeDesc.append("the "+bday+CMath.numAppendage(bday)); timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]); if(C.getYearNames().length>0) timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year)); results.append(timeDesc.toString()); } break; } case 6: // isgood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) { Faction.FactionRange FR=CMLib.factions().getRange(CMLib.factions().AlignID(),((MOB)E).fetchFaction(CMLib.factions().AlignID())); if(FR!=null) results.append(FR.name()); else results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID())); } break; } case 8: // isevil { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(CMStrings.capitalizeAndLower(CMLib.flags().getAlignmentName(E)).toLowerCase()); break; } case 9: // isneutral { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID())); break; } case 11: // isimmort results.append("[unimplemented function]"); break; case 54: // isalive { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) results.append(((MOB)E).healthText(null)); else results.append(E.name()+" is dead."); break; } case 58: // isable { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) { String s=((MOB)E).fetchExpertise(X.ID()); if(s!=null) results.append(s); } else { Ability A=((MOB)E).findAbility(arg2); if(A!=null) results.append(""+A.proficiency()); } } break; } case 59: // isopen { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); boolean returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } results.append(""+returnable); break; } case 60: // islocked { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) results.append(((Container)E).keyName()); else if((E!=null)&&(E instanceof Exit)) results.append(((Exit)E).keyName()); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) results.append(E.keyName()); } break; } case 62: // callfunc { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); String found=null; boolean validFunc=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) scriptableError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else results.append(found); break; } case 61: // strin { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Vector V=CMParms.parse(arg1.toUpperCase()); results.append(V.indexOf(arg2.toUpperCase())); break; } case 55: // ispkill { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) results.append("false"); else if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL)) results.append("true"); else results.append("false"); break; } case 10: // isfight { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat())) results.append(((MOB)E).getVictim().name()); break; } case 12: // ischarmed { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { Vector V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING); for(int v=0;v<V.size();v++) results.append((((Ability)V.elementAt(v)).name())+" "); } break; } case 15: // isfollow { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null) &&(((MOB)E).amFollowing().location()==lastKnownLocation)) results.append(((MOB)E).amFollowing().name()); break; } case 73: // isservant { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0)) results.append(((MOB)E).getLiegeID()); break; } case 56: // name case 7: // isname { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.name()); break; } case 75: // currency { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null)results.append(CMLib.beanCounter().getCurrency(E)); break; } case 14: // affected { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { if(((MOB)E).numAllEffects()>0) results.append(E.fetchEffect(CMLib.dice().roll(1,((MOB)E).numAllEffects(),-1)).name()); } else if((E!=null)&&(E.numEffects()>0)) results.append(E.fetchEffect(CMLib.dice().roll(1,E.numEffects(),-1)).name()); break; } case 69: // isbehave { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) for(int i=0;i<E.numBehaviors();i++) results.append(E.fetchBehavior(i).ID()+" "); break; } case 70: // ipaddress { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) results.append(((MOB)E).session().getAddress()); break; } case 28: // questwinner case 29: // questmob case 31: // isquestmobalive results.append("[unimplemented function]"); break; case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); int num=0; Vector MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } results.append(num); break; } case 33: // nummobs { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Vector MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } }catch(NoSuchElementException nse){} results.append(num); break; } case 34: // numracesinarea { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Room R=null; MOB M=null; for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } results.append(num); break; } case 35: // numraces { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Room R=null; MOB M=null; try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } }catch(NoSuchElementException nse){} results.append(num); break; } case 30: // questobj results.append("[unimplemented function]"); break; case 16: // hitprcnt { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); int val1=(int)Math.round(hitPctD*100.0); results.append(val1); } break; } case 50: // isseason { if(monster.location()!=null) results.append(TimeClock.SEASON_DESCS[monster.location().getArea().getTimeObj().getSeasonCode()]); break; } case 51: // isweather { if(monster.location()!=null) results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]); break; } case 57: // ismoon { if(monster.location()!=null) results.append(TimeClock.PHASE_DESC[monster.location().getArea().getTimeObj().getMoonPhase()]); break; } case 38: // istime { if(lastKnownLocation!=null) results.append(TimeClock.TOD_DESC[lastKnownLocation.getArea().getTimeObj().getTODCode()].toLowerCase()); break; } case 39: // isday { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth()); break; } case 43: // roommob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); if(which!=null) results.append(which.name()); break; } case 44: // roomitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which=I; break;} ct++; } } if(which!=null) results.append(which.name()); break; } case 45: // nummobsroom { int num=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if((name.length()>0)&&(!name.equalsIgnoreCase("*"))) { num=0; Vector MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } results.append(""+num); break; } case 63: // numpcsroom { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.numPCInhabitants()); break; } case 79: // numpcsarea { if(lastKnownLocation!=null) { int num=0; for(int s=0;s<CMLib.sessions().size();s++) { Session S=CMLib.sessions().elementAt(s); if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } results.append(""+num); } break; } case 77: // explored { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { Area A=null; if(!where.equalsIgnoreCase("world")) { Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 instanceof Area) A=(Area)E2; else A=CMLib.map().getArea(where); } if((lastKnownLocation!=null) &&((A!=null)||(where.equalsIgnoreCase("world")))) { int pct=0; MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); results.append(""+pct); } } break; } case 72: // faction { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Faction F=CMLib.factions().getFaction(arg2); if(F==null) scriptableError(scripted,"FACTION","Unknown Faction",arg1); else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID()))) { int value=((MOB)E).fetchFaction(F.factionID()); Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),value); if(FR!=null) results.append(FR.name()); } break; } case 46: // numitemsroom { int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 47: //mobitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); Item which=null; int ct=1; if(M!=null) for(int i=0;i<M.inventorySize();i++) { Item I=M.fetchInventory(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which=I; break;} ct++; } } if(which!=null) results.append(which.name()); break; } case 48: // numitemsmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); MOB which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); int ct=1; if(which!=null) for(int i=0;i<which.inventorySize();i++) { Item I=which.fetchInventory(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 36: // ishere { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().name()); break; } case 17: // inroom { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(CMLib.map().getExtendedRoomID(lastKnownLocation)); else results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E))); break; } case 90: // inarea { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name()); else { Room R=CMLib.map().roomLocation(E); results.append(R==null?"Nowhere":R.getArea().Name()); } break; } case 89: // isrecall { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E))); break; } case 37: // inlocale { String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(parms.trim().length()==0) { if(lastKnownLocation!=null) results.append(lastKnownLocation.name()); } else { Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { Room R=CMLib.map().roomLocation(E); if(R!=null) results.append(R.name()); } } break; } case 18: // sex { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().genderName()); break; } case 91: // datetime { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) scriptableError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) switch(index) { case 2: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 3: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 4: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth()); break; case 5: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear()); break; default: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay()); break; } break; } case 13: // stat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String val=getStatValue(E,arg2); if(val==null) { scriptableError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 52: // gstat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String val=getGStatValue(E,arg2); if(val==null) { scriptableError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 19: // position { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex="STANDING"; if(CMLib.flags().isSleeping(E)) sex="SLEEPING"; else if(CMLib.flags().isSitting(E)) sex="SITTING"; results.append(sex); break; } break; } case 20: // level { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.envStats().level()); break; } case 80: // questpoints { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getQuestPoint()); break; } case 83: // qvar { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if((arg1.length()!=0)&&(arg2.length()!=0)) { Quest Q=getQuest(arg1); if(Q!=null) results.append(Q.getStat(arg2)); } break; } case 84: // math { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); results.append(""+Math.round(CMath.s_parseMathExpression(arg1))); break; } case 85: // islike { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); results.append(CMLib.masking().maskDesc(arg1)); break; } case 86: // strcontains { results.append("[unimplemented function]"); break; } case 81: // trains { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getTrains()); break; } case 92: // isodd { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } if( isodd ) { results.append( CMath.s_long( val.trim() ) ); } break; } case 82: // pracs { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getPractices()); break; } case 68: // clandata { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((E!=null)&&(E instanceof MOB)) clanID=((MOB)E).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); Clan C=CMLib.clans().findClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(arg2.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} String whichVal=""; switch(whichVar) { case 0: whichVal=C.getAcceptanceSettings(); break; case 1: whichVal=C.getDetail(monster); break; case 2: whichVal=C.getDonation(); break; case 3: whichVal=""+C.getExp(); break; case 4: whichVal=Clan.GVT_DESCS[C.getGovernment()]; break; case 5: whichVal=C.getMorgue(); break; case 6: whichVal=C.getPolitics(); break; case 7: whichVal=C.getPremise(); break; case 8: whichVal=C.getRecall(); break; case 9: whichVal=""+C.getSize(); break; // size case 10: whichVal=Clan.CLANSTATUS_DESC[C.getStatus()]; break; case 11: whichVal=""+C.getTaxes(); break; case 12: whichVal=""+C.getTrophies(); break; case 13: whichVal=""+C.getType(); break; // type case 14: { Vector areas=C.getControlledAreas(); StringBuffer list=new StringBuffer(""); for(int i=0;i<areas.size();i++) list.append("\""+((Environmental)areas.elementAt(i)).name()+"\" "); whichVal=list.toString().trim(); break; // areas } case 15: { DVector members=C.getMemberList(); StringBuffer list=new StringBuffer(""); for(int i=0;i<members.size();i++) list.append("\""+((String)members.elementAt(i,1))+"\" "); whichVal=list.toString().trim(); break; // memberlist } case 16: MOB M=C.getResponsibleMember(); if(M!=null) whichVal=M.Name(); break; // topmember default: scriptableError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); break; } results.append(whichVal); } break; } case 67: // hastitle { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)) { MOB M=(MOB)E; results.append(M.playerStats().getActiveTitle()); } break; } case 66: // clanrank { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).getClanRole()+""); break; } case 21: // class { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().displayClassName()); break; } case 64: // deity { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex=((MOB)E).getWorshipCharID(); results.append(sex); } break; } case 65: // clan { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex=((MOB)E).getClanID(); results.append(sex); } break; } case 88: // mood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(E.fetchEffect("Mood")!=null)) results.append(CMStrings.capitalizeAndLower(E.fetchEffect("Mood").text())); break; } case 22: // baseclass { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getCurrentClass().baseClass()); break; } case 23: // race { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().raceName()); break; } case 24: //racecat { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getMyRace().racialCategory()); break; } case 25: // goldamt { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return results.toString(); } results.append(val1); } break; } case 78: // exp { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=((MOB)E).getExperience(); results.append(val1); } break; } case 76: // value { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { scriptableError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); return results.toString(); } Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2)); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return results.toString(); } results.append(val1); } break; } case 26: // objtype { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String sex=CMClass.classID(E).toLowerCase(); results.append(sex); } break; } case 53: // incontainer { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(((MOB)E).riding()!=null) results.append(((MOB)E).riding().Name()); } else if(E instanceof Item) { if(((Item)E).riding()!=null) results.append(((Item)E).riding().Name()); else if(((Item)E).container()!=null) results.append(((Item)E).container().Name()); else if(E instanceof Container) { Vector V=((Container)E).getContents(); for(int v=0;v<V.size();v++) results.append("\""+((Item)V.elementAt(v)).Name()+"\" "); } } } break; } case 27: // var { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0).toUpperCase(); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); results.append(val); break; } case 41: // eval results.append("[unimplemented function]"); break; case 40: // number { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) if(!Character.isDigit(val.charAt(i))) { isnumber=false; break;} if(isnumber) results.append(CMath.s_long(val.trim())); break; } case 42: // randnum { String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,0)); break; } case 71: // rand0num { String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,-1)); break; } default: scriptableError(scripted,"Unknown Val",preFab,evaluable); return results.toString(); } } if((z>=0)&&(z<=evaluable.length())) { evaluable=evaluable.substring(z+1).trim(); uevaluable=uevaluable.substring(z+1).trim(); } } return results.toString(); } protected MOB getRandPC(MOB monster, Object[] tmp, Room room) { if((tmp[10]==null)||(tmp[10]==monster)) { MOB M=null; if(room!=null) { Vector choices = new Vector(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if((!M.isMonster())&&(M!=monster)) { HashSet seen=new HashSet(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.addElement(M); } } if(choices.size() > 0) tmp[10] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[10]; } protected MOB getRandAnyone(MOB monster, Object[] tmp, Room room) { if((tmp[11]==null)||(tmp[11]==monster)) { MOB M=null; if(room!=null) { Vector choices = new Vector(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if(M!=monster) { HashSet seen=new HashSet(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.addElement(M); } } if(choices.size() > 0) tmp[11] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[11]; } public String execute(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, Vector script, String msg, Object[] tmp) { tickStatus=Tickable.STATUS_START; for(int si=1;si<script.size();si++) { String s=((String)script.elementAt(si)).trim(); String cmd=CMParms.getCleanBit(s,0).toUpperCase(); Integer methCode=(Integer)methH.get(cmd); if((methCode==null)&&(cmd.startsWith("MP"))) for(int i=0;i<methods.length;i++) if(methods[i].startsWith(cmd)) methCode=new Integer(i); if(methCode==null) methCode=new Integer(0); tickStatus=Tickable.STATUS_MISC3+methCode.intValue(); if(cmd.length()==0) continue; switch(methCode.intValue()) { case 57: // <SCRIPT> { StringBuffer jscript=new StringBuffer(""); while((++si)<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equalsIgnoreCase("</SCRIPT>")) break; jscript.append(s+"\n"); } if(CMSecurity.isApprovedJScript(jscript)) { Context cx = Context.enter(); try { JScriptEvent scope = new JScriptEvent(scripted,source,target,monster,primaryItem,secondaryItem,msg); cx.initStandardObjects(scope); String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString","setPlayerSetOverride"}; scope.defineFunctionProperties(names, JScriptEvent.class, ScriptableObject.DONTENUM); cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null); } catch(Exception e) { Log.errOut("Scriptable",scripted.name()+"/"+CMLib.map().getExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage()); } Context.exit(); } else if(CMProps.getIntVar(CMProps.SYSTEMI_JSCRIPTS)==1) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,"A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script."); } break; } case 19: // if { String conditionStr=(s.substring(2).trim()); boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,conditionStr); Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundendif=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("ENDIF")&&(depth==0)) { foundendif=true; break; } else if(cmd.equals("ELSE")&&(depth==0)) { condition=!condition; if(s.substring(4).trim().length()>0) { script.setElementAt("ELSE",si); script.insertElementAt(s.substring(4).trim(),si+1); } } else { if(condition) V.addElement(s); if(cmd.equals("IF")) depth++; else if(cmd.equals("ENDIF")) depth--; } si++; } if(!foundendif) { scriptableError(scripted,"IF","Syntax"," Without ENDIF!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { //source.tell("Starting "+conditionStr); //for(int v=0;v<V.size();v++) // source.tell("Statement "+((String)V.elementAt(v))); String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } //source.tell("Stopping "+conditionStr); } break; } case 70: // switch { String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)).trim(); Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundendif=false; boolean ignoreUntilEndScript=false; boolean inCase=false; boolean matchedCase=false; si++; String s2=null; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("ENDSWITCH")&&(depth==0)) { foundendif=true; break; } else if(cmd.equals("CASE")&&(depth==0)) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)).trim(); inCase=var.equalsIgnoreCase(s2); matchedCase=matchedCase||inCase; } else if(cmd.equals("DEFAULT")&&(depth==0)) { inCase=!matchedCase; } else { if(inCase) V.addElement(s); if(cmd.equals("SWITCH")) depth++; else if(cmd.equals("ENDSWITCH")) depth--; } si++; } if(!foundendif) { scriptableError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } } break; } case 62: // for x = 1 to 100 { if(CMParms.numBits(s)<6) { scriptableError(scripted,"FOR","Syntax","5 parms required!"); tickStatus=Tickable.STATUS_END; return null; } String varStr=CMParms.getBit(s,1); if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1)))) { scriptableError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2.."); tickStatus=Tickable.STATUS_END; return null; } int whichVar=CMath.s_int(Character.toString(varStr.charAt(1))); if((tmp[whichVar] instanceof String) &&(((String)tmp[whichVar]).length()>1) &&(((String)tmp[whichVar]).startsWith(" ")) &&(CMath.isInteger(((String)tmp[whichVar]).trim()))) { scriptableError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!"); tickStatus=Tickable.STATUS_END; return null; } if((!CMParms.getBit(s,2).equals("="))&&(!CMParms.getBit(s,4).equalsIgnoreCase("to"))) { scriptableError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3).trim()).trim(); String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,4).trim()).trim(); if((!CMath.isInteger(from))||(!CMath.isInteger(to))) { scriptableError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!"); tickStatus=Tickable.STATUS_END; return null; } Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundnext=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("NEXT")&&(depth==0)) { foundnext=true; break; } else { V.addElement(s); if(cmd.equals("FOR")) depth++; else if(cmd.equals("NEXT")) depth--; } si++; } if(!foundnext) { scriptableError(scripted,"FOR","Syntax"," Without NEXT!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { //source.tell("Starting "+conditionStr); //for(int v=0;v<V.size();v++) // source.tell("Statement "+((String)V.elementAt(v))); int toInt=CMath.s_int(to); int fromInt=CMath.s_int(from); int increment=(toInt>=fromInt)?1:-1; String response=null; for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment) { tmp[whichVar]=" "+forLoop; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) break; } tmp[whichVar]=" "+toInt; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } tmp[whichVar]=null; //source.tell("Stopping "+conditionStr); } break; } case 50: // break; tickStatus=Tickable.STATUS_END; return null; case 1: // mpasound { String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(8).trim()); //lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo); for(int d=0;d<Directions.NUM_DIRECTIONS;d++) { Room R2=lastKnownLocation.getRoomInDir(d); Exit E2=lastKnownLocation.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(E2.isOpen())) R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo); } break; } case 4: // mpjunk { if(s.substring(6).trim().equalsIgnoreCase("all")) { while(monster.inventorySize()>0) { Item I=monster.fetchInventory(0); if(I!=null) { if(I.owner()==null) I.setOwner(monster); I.destroy(); } else break; } } else { Environmental E=getArgumentItem(s.substring(6).trim(),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Item I=null; if(E instanceof Item) I=(Item)E; if(I==null) I=monster.fetchInventory(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); if((I==null)&&(scripted instanceof Room)) I=((Room)scripted).fetchAnyItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); if(I!=null) I.destroy(); } break; } case 2: // mpecho { if(lastKnownLocation!=null) lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); break; } case 13: // mpunaffect { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String which=CMParms.getPastBitClean(s,1); if(newTarget!=null) if(which.equalsIgnoreCase("all")||(which.length()==0)) { for(int a=newTarget.numEffects()-1;a>=0;a--) { Ability A=newTarget.fetchEffect(a); if(A!=null) A.unInvoke(); } } else { Ability A=newTarget.fetchEffect(which); if(A!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPUNAFFECTED by "+A.Name()); A.unInvoke(); if(newTarget.fetchEffect(which)==A) newTarget.delEffect(A); } } break; } case 3: // mpslay { Environmental newTarget=getArgumentItem(CMParms.getPastBitClean(s,0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) CMLib.combat().postDeath(monster,(MOB)newTarget,null); break; } case 16: // mpset { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getCleanBit(s,2); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(arg2,arg3); found=true; break; } } if((!found)&&(newTarget instanceof MOB)) { MOB M=(MOB)newTarget; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } if(!found) for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++) if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1); M.baseEnvStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } if(!found) { scriptableError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverEnvStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { ((MOB)newTarget).baseCharStats().getCurrentClass().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverEnvStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 63: // mpargset { String arg1=CMParms.getCleanBit(s,1); String arg2=CMParms.getPastBitClean(s,1); if((arg1.length()!=2)||(!arg1.startsWith("$"))) { scriptableError(scripted,"MPARGSET","Syntax","Invalid argument var: "+arg1+" for "+scripted.Name()); break; } Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(O==null) O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((O==null) &&((!arg2.trim().startsWith("$")) ||(arg2.length()<2) ||((!Character.isDigit(arg2.charAt(1))) &&(!Character.isLetter(arg2.charAt(1)))))) O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2); char c=arg1.charAt(1); if(Character.isDigit(c)) { if((O instanceof String)&&(((String)O).equalsIgnoreCase("null"))) O=null; tmp[CMath.s_int(Character.toString(c))]=O; } else switch(arg1.charAt(1)) { case 'N': case 'n': if(O instanceof MOB) source=(MOB)O; break; case 'B': case 'b': if(O instanceof Environmental) lastLoaded=(Environmental)O; break; case 'I': case 'i': if(O instanceof Environmental) scripted=(Environmental)O; if(O instanceof MOB) monster=(MOB)O; break; case 'T': case 't': if(O instanceof Environmental) target=(Environmental)O; break; case 'O': case 'o': if(O instanceof Item) primaryItem=(Item)O; break; case 'P': case 'p': if(O instanceof Item) secondaryItem=(Item)O; break; case 'd': case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break; default: scriptableError(scripted,"MPARGSET","Syntax","Invalid argument var: "+arg1+" for "+scripted.Name()); break; } break; } case 35: // mpgset { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getCleanBit(s,2); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(newTarget.getStatCodes()[i],arg3); found=true; break; } } if(!found) if(newTarget instanceof MOB) { for(int i=0;i<CMObjectBuilder.GENMOBCODES.length;i++) { if(CMObjectBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i]))-1); CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i],arg3); found=true; break; } } if(!found) { MOB M=(MOB)newTarget; for(int i=0;i<CharStats.STAT_DESCS.length;i++) { if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0)))) M.baseCharStats().setStat(i,arg3.charAt(0)); else M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } if(!found) for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++) { if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1); M.baseEnvStats().setStat(arg2,arg3); found=true; break; } } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } } else if(newTarget instanceof Item) { for(int i=0;i<CMObjectBuilder.GENITEMCODES.length;i++) { if(CMObjectBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i]))-1); CMLib.coffeeMaker().setGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i],arg3); found=true; break; } } } if(!found) { scriptableError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverEnvStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { ((MOB)newTarget).baseCharStats().getCurrentClass().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverEnvStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 11: // mpexp { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { int baseLevel=newTarget.baseEnvStats().level(); int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience(baseLevel-1); int thisLevelExpNeeded=CMLib.leveler().getLevelExperience(baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false); } break; } case 59: // mpquestpoints { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setQuestPoint(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 65: // MPQSET { String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); Environmental obj=getArgumentItem(CMParms.getPastBitClean(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Quest Q=getQuest(qstr); if(Q==null) scriptableError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name()); else if(var.equalsIgnoreCase("QUESTOBJ")) { if(obj==null) scriptableError(scripted,"MPQSET","Syntax","Unknown object "+CMParms.getPastBitClean(s,2)+" for "+scripted.Name()); else { obj.baseEnvStats().setDisposition(obj.baseEnvStats().disposition()|EnvStats.IS_UNSAVABLE); obj.recoverEnvStats(); Q.runtimeRegisterObject(obj); } } else { if(val.equals("++")) val=""+(CMath.s_int(Q.getStat(var))+1); if(val.equals("--")) val=""+(CMath.s_int(Q.getStat(var))-1); Q.setStat(var,val); } break; } case 66: // MPLOG { String type=CMParms.getCleanBit(s,1).toUpperCase(); String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); if(type.startsWith("E")) Log.errOut(head,val); else if(type.startsWith("I")||type.startsWith("S")) Log.infoOut(head,val); else if(type.startsWith("D")) Log.debugOut(head,val); else scriptableError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name()); break; } case 67: // MPCHANNEL { String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); boolean sysmsg=channel.startsWith("!"); if(sysmsg) channel=channel.substring(1); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(CMLib.channels().getChannelCodeNumber(channel)<0) scriptableError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name()); else CMLib.commands().postChannel(monster,channel,val,sysmsg); break; } case 68: // unload { String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); if(!new CMFile(Resources.makeFileResourceName(scriptname),null,false,true).exists()) scriptableError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname)); else { Vector delThese=new Vector(); boolean foundKey=false; scriptname=scriptname.toUpperCase().trim(); String parmname=scriptname; Vector V=Resources.findResourceKeys(parmname); for(Enumeration e=V.elements();e.hasMoreElements();) { String key=(String)e.nextElement(); if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname))) { foundKey=true; delThese.addElement(key);} } if(foundKey) for(int i=0;i<delThese.size();i++) Resources.removeResource((String)delThese.elementAt(i)); } break; } case 60: // trains { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setTrains(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 61: // pracs { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setPractices(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 5: // mpmload { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Vector Ms=new Vector(); MOB m=CMClass.getMOB(s); if(m!=null) Ms.addElement(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(s,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.elementAt(i) instanceof MOB) { m=(MOB)((MOB)Ms.elementAt(i)).copyOf(); m.text(); m.recoverEnvStats(); m.recoverCharStats(); m.resetToMaxState(); m.bringToLife(lastKnownLocation,true); lastLoaded=m; } } } break; } case 6: // mpoload { // if not mob if(scripted instanceof MOB) { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); int containerIndex=s.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { Vector containers=new Vector(); findSomethingCalledThis(s.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) if((containers.elementAt(c) instanceof Container) &&(((Container)containers.elementAt(c)).capacity()>0)) { container=(Container)containers.elementAt(c); s=s.substring(0,containerIndex).trim(); break; } } long coins=CMLib.english().numPossibleGold(null,s); if(coins>0) { String currency=CMLib.english().numPossibleGoldCurrency(scripted,s); double denom=CMLib.english().numPossibleGoldDenomination(scripted,currency,s); Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); monster.addInventory(C); C.putCoinsBack(); } else if(lastKnownLocation!=null) { Vector Is=new Vector(); Item m=CMClass.getItem(s); if(m!=null) Is.addElement(m); else findSomethingCalledThis(s,(MOB)scripted,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.elementAt(i) instanceof Item) { m=(Item)Is.elementAt(i); if((m!=null)&&(!(m instanceof ArchonOnly))) { m=(Item)m.copyOf(); m.recoverEnvStats(); m.setContainer(container); if(container instanceof MOB) ((MOB)container.owner()).addInventory(m); else if(container instanceof Room) ((Room)container.owner()).addItemRefuse(m,Item.REFUSE_PLAYER_DROP); else monster.addInventory(m); lastLoaded=m; } } } lastKnownLocation.recoverRoomStats(); monster.recoverCharStats(); monster.recoverEnvStats(); monster.recoverMaxState(); } } break; } case 41: // mpoloadroom { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); if(lastKnownLocation!=null) { Vector Is=new Vector(); int containerIndex=s.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { Vector containers=new Vector(); findSomethingCalledThis(s.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) if((containers.elementAt(c) instanceof Container) &&(((Container)containers.elementAt(c)).capacity()>0)) { container=(Container)containers.elementAt(c); s=s.substring(0,containerIndex).trim(); break; } } long coins=CMLib.english().numPossibleGold(null,s); if(coins>0) { String currency=CMLib.english().numPossibleGoldCurrency(monster,s); double denom=CMLib.english().numPossibleGoldDenomination(monster,currency,s); Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); Is.addElement(C); } else { Item I=CMClass.getItem(s); if(I!=null) Is.addElement(I); else findSomethingCalledThis(s,monster,lastKnownLocation,Is,false); } for(int i=0;i<Is.size();i++) { if(Is.elementAt(i) instanceof Item) { Item I=(Item)Is.elementAt(i); if((I!=null)&&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverEnvStats(); lastKnownLocation.addItemRefuse(I,Item.REFUSE_MONSTER_EQ); I.setContainer(container); if(I instanceof Coins) ((Coins)I).putCoinsBack(); if(I instanceof RawMaterial) ((RawMaterial)I).rebundle(); lastLoaded=I; } } } lastKnownLocation.recoverRoomStats(); } break; } case 42: // mphide { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()|EnvStats.IS_NOT_SEEN); newTarget.recoverEnvStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 58: // mpreset { String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)); if(arg.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) CMLib.map().resetArea(lastKnownLocation.getArea()); } else if(arg.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.map().resetRoom(lastKnownLocation); } else { Room R=CMLib.map().getRoom(arg); if(R!=null) CMLib.map().resetRoom(R); else { Area A=CMLib.map().findArea(arg); if(A!=null) CMLib.map().resetArea(A); else scriptableError(scripted,"MPRESET","Syntax","Unknown location: "+arg+" for "+scripted.Name()); } } break; } case 56: // mpstop { Vector V=new Vector(); String who=CMParms.getCleanBit(s,1); if(who.equalsIgnoreCase("all")) { for(int i=0;i<lastKnownLocation.numInhabitants();i++) V.addElement(lastKnownLocation.fetchInhabitant(i)); } else { Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget instanceof MOB) V.addElement(newTarget); } for(int v=0;v<V.size();v++) { Environmental newTarget=(Environmental)V.elementAt(v); if(newTarget instanceof MOB) { MOB mob=(MOB)newTarget; Ability A=null; for(int a=mob.numEffects()-1;a>=0;a--) { A=mob.fetchEffect(a); if((A!=null) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL) &&(A.canBeUninvoked()) &&(!A.isAutoInvoked())) A.unInvoke(); } mob.makePeace(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } } break; } case 43: // mpunhide { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(CMath.bset(newTarget.baseEnvStats().disposition(),EnvStats.IS_NOT_SEEN))) { newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()-EnvStats.IS_NOT_SEEN); newTarget.recoverEnvStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 44: // mpopen { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALid())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),true,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 45: // mpclose { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())&&(((Exit)newTarget).isOpen())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALid())&&(((Container)newTarget).isOpen())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 46: // mplock { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasALock())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALock())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),true); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 47: // mpunlock { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).isLocked())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).isLocked())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 48: // return tickStatus=Tickable.STATUS_END; return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim()); case 7: // mpechoat { String parm=CMParms.getCleanBit(s,1); Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { s=CMParms.getPastBit(s,1).trim(); if(newTarget==monster) lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); else lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s),CMMsg.NO_EFFECT,null); } else if(parm.equalsIgnoreCase("world")) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } } else if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null)) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } } else if(CMLib.map().getRoom(parm)!=null) CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); else if(CMLib.map().findArea(parm)!=null) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); } } break; } case 8: // mpechoaround { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { s=CMParms.getPastBit(s,1).trim(); lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } break; } case 9: // mpcast { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { A.setProficiency(100); A.invoke(monster,newTarget,false,0); } break; } case 30: // mpaffect { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPAFFECTED by "+A.Name()); A.setMiscText(m2); if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY) newTarget.addNonUninvokableEffect(A); else A.invoke(monster,CMParms.parse(m2),newTarget,true,0); } break; } case 31: // mpbehave { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Behavior A=null; if((cast!=null)&&(newTarget!=null)) { A=newTarget.fetchBehavior(cast); if(A==null) A=CMClass.getBehavior(cast); } if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPBEHAVED with "+A.name()); A.setParms(m2); if(newTarget.fetchBehavior(A.ID())==null) newTarget.addBehavior(A); } break; } case 32: // mpunbehave { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { Behavior A=newTarget.fetchBehavior(cast); if(A!=null) newTarget.delBehavior(A); if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scriptable",newTarget.Name()+" was MPUNBEHAVED with "+A.name()); } break; } case 33: // mptattoo { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); String tattoo=tattooName; if((tattoo.length()>0) &&(Character.isDigit(tattoo.charAt(0))) &&(tattoo.indexOf(" ")>0) &&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim()))) tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim(); if(themob.fetchTattoo(tattoo)!=null) { if(tattooMinus) themob.delTattoo(tattooName); } else if(!tattooMinus) themob.addTattoo(tattooName); } break; } case 55: // mpnotrigger { String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); int triggerCode=-1; for(int i=0;i<progs.length;i++) if(trigger.equalsIgnoreCase(progs[i])) triggerCode=i; if(triggerCode<0) scriptableError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name."); else if(!CMath.isInteger(time.trim())) scriptableError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time."); else { noTrigger.remove(new Integer(triggerCode)); noTrigger.put(new Integer(triggerCode),new Long(System.currentTimeMillis()+CMath.s_long(time.trim()))); } break; } case 54: // mpfaction { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Faction F=CMLib.factions().getFaction(faction); if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim()))) range=""+(themob.fetchFaction(faction)-CMath.s_int(range.substring(2).trim())); else if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim()))) range=""+(themob.fetchFaction(faction)+CMath.s_int(range.substring(1).trim())); if(CMath.isInteger(range.trim())) themob.addFaction(F.factionID(),CMath.s_int(range.trim())); else { Vector V=CMLib.factions().getRanges(F.factionID()); Faction.FactionRange FR=null; for(int v=0;v<V.size();v++) { Faction.FactionRange FR2=(Faction.FactionRange)V.elementAt(v); if(FR2.name().equalsIgnoreCase(range)) { FR=FR2; break;} } if(FR==null) scriptableError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+"."); else themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2)); } } break; } case 49: // mptitle { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=CMParms.getPastBitClean(s,1); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); String tattoo=tattooName; if((tattoo.length()>0) &&(Character.isDigit(tattoo.charAt(0))) &&(tattoo.indexOf(" ")>0) &&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim()))) tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim(); if(themob.playerStats()!=null) { if(themob.playerStats().getTitles().contains(tattoo)) { if(tattooMinus) themob.playerStats().getTitles().removeElement(tattooName); } else if(!tattooMinus) themob.playerStats().getTitles().insertElementAt(tattooName,0); } } break; } case 10: // mpkill { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) monster.setVictim((MOB)newTarget); break; } case 51: // mpsetclandata { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((newTarget!=null)&&(newTarget instanceof MOB)) clanID=((MOB)newTarget).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String clanvar=CMParms.getCleanBit(s,2); String clanval=CMParms.getPastBitClean(s,2); Clan C=CMLib.clans().getClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(clanvar.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} boolean nosave=false; switch(whichVar) { case 0: C.setAcceptanceSettings(clanval); break; case 1: nosave=true; break; // detail case 2: C.setDonation(clanval); break; case 3: C.setExp(CMath.s_long(clanval.trim())); break; case 4: C.setGovernment(CMath.s_int(clanval.trim())); break; case 5: C.setMorgue(clanval); break; case 6: C.setPolitics(clanval); break; case 7: C.setPremise(clanval); break; case 8: C.setRecall(clanval); break; case 9: nosave=true; break; // size case 10: C.setStatus(CMath.s_int(clanval.trim())); break; case 11: C.setTaxes(CMath.s_double(clanval.trim())); break; case 12: C.setTrophies(CMath.s_int(clanval.trim())); break; case 13: nosave=true; break; // type case 14: nosave=true; break; // areas case 15: nosave=true; break; // memberlist case 16: nosave=true; break; // topmember default: scriptableError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable."); nosave=true; break; } if(!nosave) C.update(); } break; } case 52: // mpplayerclass { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) { Vector V=CMParms.parse(CMParms.getPastBit(s,1)); for(int i=0;i<V.size();i++) { if(CMath.isInteger(((String)V.elementAt(i)).trim())) ((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(((String)V.elementAt(i)).trim())); else { CharClass C=CMClass.findCharClass((String)V.elementAt(i)); if(C!=null) ((MOB)newTarget).baseCharStats().setCurrentClass(C); } } ((MOB)newTarget).recoverCharStats(); } break; } case 12: // mppurge { if(lastKnownLocation!=null) { String s2=CMParms.getPastBitClean(s,0).trim(); Environmental E=null; if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me")) E=scripted; else E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(!((MOB)E).isMonster()) { if(((MOB)E).getStartRoom()!=null) ((MOB)E).getStartRoom().bringMobHere((MOB)E,false); ((MOB)E).session().setKillFlag(true); } else if(((MOB)E).getStartRoom()!=null) ((MOB)E).killMeDead(false); else ((MOB)E).destroy(); } else if(E instanceof Item) { Environmental oE=((Item)E).owner(); ((Item)E).destroy(); if(oE!=null) oE.recoverEnvStats(); } } lastKnownLocation.recoverRoomStats(); } break; } case 14: // mpgoto { s=s.substring(6).trim(); if((s.length()>0)&&(lastKnownLocation!=null)) { Room goHere=null; if(s.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(s,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s),lastKnownLocation); if(goHere!=null) { if(scripted instanceof MOB) goHere.bringMobHere((MOB)scripted,true); else if(scripted instanceof Item) goHere.bringItemHere((Item)scripted,Item.REFUSE_PLAYER_DROP,true); else { goHere.bringMobHere(monster,true); if(!(scripted instanceof MOB)) goHere.delInhabitant(monster); } if(CMLib.map().roomLocation(scripted)==goHere) lastKnownLocation=goHere; } } break; } case 15: // mpat if(lastKnownLocation!=null) { Room lastPlace=lastKnownLocation; String roomName=CMParms.getCleanBit(s,1); if(roomName.length()>0) { s=CMParms.getPastBit(s,1).trim(); Room goHere=null; if(roomName.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(goHere!=null) { goHere.bringMobHere(monster,true); Vector V=new Vector(); V.addElement(""); V.addElement(s.trim()); lastKnownLocation=goHere; execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); lastKnownLocation=lastPlace; lastPlace.bringMobHere(monster,true); if(!(scripted instanceof MOB)) { goHere.delInhabitant(monster); lastPlace.delInhabitant(monster); } } } } break; case 17: // mptransfer { String mobName=CMParms.getCleanBit(s,1); String roomName=""; Room newRoom=null; if(CMParms.numBits(s)>2) { roomName=CMParms.getPastBit(s,1); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); } if((roomName.length()==0)&&(lastKnownLocation!=null)) roomName=lastKnownLocation.roomID(); if(roomName.length()>0) { if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom!=null) { Vector V=new Vector(); if(mobName.startsWith("$")) { Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) V.addElement(E); } if(V.size()==0) { mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName); if(mobName.equalsIgnoreCase("all")) { if(lastKnownLocation!=null) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!V.contains(m))) V.addElement(m); } } } else { MOB findOne=null; Area A=null; if(lastKnownLocation!=null) { findOne=lastKnownLocation.fetchInhabitant(mobName); A=lastKnownLocation.getArea(); if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } if(findOne==null) { findOne=CMLib.map().getPlayer(mobName); if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true))) findOne=null; if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } if((findOne==null)&&(A!=null)) for(Enumeration r=A.getProperMap();r.hasMoreElements();) { Room R=(Room)r.nextElement(); findOne=R.fetchInhabitant(mobName); if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } } } for(int v=0;v<V.size();v++) { if(V.elementAt(v) instanceof MOB) { MOB mob=(MOB)V.elementAt(v); HashSet H=mob.getGroupMembers(new HashSet()); for(Iterator e=H.iterator();e.hasNext();) { MOB M=(MOB)e.next(); if((!V.contains(M))&&(M.location()==mob.location())) V.addElement(M); } } } for(int v=0;v<V.size();v++) { if(V.elementAt(v) instanceof MOB) { MOB follower=(MOB)V.elementAt(v); Room thisRoom=follower.location(); // scripting guide calls for NO text -- empty is probably req tho CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMProps.msp("appear.wav",10)); CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE," "); if(thisRoom.okMessage(follower,leaveMsg)&&newRoom.okMessage(follower,enterMsg)) { if(follower.isInCombat()) { CMLib.commands().postFlee(follower,("NOWHERE")); follower.makePeace(); } thisRoom.send(follower,leaveMsg); newRoom.bringMobHere(follower,false); newRoom.send(follower,enterMsg); follower.tell("\n\r\n\r"); CMLib.commands().postLook(follower,true); } } else if((V.elementAt(v) instanceof Item) &&(newRoom!=CMLib.map().roomLocation((Environmental)V.elementAt(v)))) newRoom.bringItemHere((Item)V.elementAt(v),Item.REFUSE_PLAYER_DROP,true); if(V.elementAt(v)==scripted) lastKnownLocation=newRoom; } } } break; } case 25: // mpbeacon { String roomName=CMParms.getCleanBit(s,1); Room newRoom=null; if((roomName.length()>0)&&(lastKnownLocation!=null)) { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1)); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if((newRoom!=null)&&(lastKnownLocation!=null)) { Vector V=new Vector(); if(s.equalsIgnoreCase("all")) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m))) V.addElement(m); } } else { MOB findOne=lastKnownLocation.fetchInhabitant(s); if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster())) V.addElement(findOne); } for(int v=0;v<V.size();v++) { MOB follower=(MOB)V.elementAt(v); if(!follower.isMonster()) follower.setStartRoom(newRoom); } } } break; } case 18: // mpforce { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1)); if((newTarget!=null)&&(newTarget instanceof MOB)) { Vector V=CMParms.parse(s); ((MOB)newTarget).doCommand(V); } break; } case 20: // mpsetvar { String which=CMParms.getCleanBit(s,1); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(!which.equals("*")) { if(E==null) which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which); else if(E instanceof Room) which=CMLib.map().getExtendedRoomID((Room)E); else which=E.Name(); } if((which.length()>0)&&(arg2.length()>0)) mpsetvar(which,arg2,arg3); break; } case 36: // mpsavevar { String which=CMParms.getCleanBit(s,1); String arg2=CMParms.getCleanBit(s,2).toUpperCase(); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if((which.length()>0)&&(arg2.length()>0)) { DVector V=getScriptVarSet(which,arg2); for(int v=0;v<V.size();v++) { which=(String)V.elementAt(0,1); arg2=((String)V.elementAt(0,2)).toUpperCase(); Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+which); String val=""; if(H!=null) { val=(String)H.get(arg2); if(val==null) val=""; } if(val.length()>0) CMLib.database().DBReCreateData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val); else CMLib.database().DBDeleteData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); } } break; } case 39: // mploadvar { String which=CMParms.getCleanBit(s,1); String arg2=CMParms.getCleanBit(s,2).toUpperCase(); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()>0) { Vector V=null; which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg2.equals("*")) V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS"); else V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); if((V!=null)&&(V.size()>0)) for(int v=0;v<V.size();v++) { Vector VAR=(Vector)V.elementAt(v); if(VAR.size()>3) { String varName=(String)VAR.elementAt(2); if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_")) varName=varName.substring((which+"_SCRIPTABLEVARS_").length()); mpsetvar(which,varName,(String)VAR.elementAt(3)); } } } break; } case 40: // MPM2I2M { String arg1=CMParms.getCleanBit(s,1); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { String arg2=""; String arg3=""; if(CMParms.numBits(s)>2) { arg2=CMParms.getCleanBit(s,2); if(CMParms.numBits(s)>3) arg3=CMParms.getPastBit(s,2); } CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged"); if(caged!=null) { ((Item)caged).baseEnvStats().setAbility(1); ((Item)caged).recoverEnvStats(); } if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null)) { if(arg2.length()>0) ((Item)caged).setName(arg2); if(arg3.length()>0) ((Item)caged).setDisplayText(arg3); lastKnownLocation.addItemRefuse((Item)caged,Item.REFUSE_PLAYER_DROP); ((MOB)E).killMeDead(false); } } else if(E instanceof CagedAnimal) { MOB M=((CagedAnimal)E).unCageMe(); if((M!=null)&&(lastKnownLocation!=null)) { M.bringToLife(lastKnownLocation,true); ((Item)E).destroy(); } } else scriptableError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item."); break; } case 28: // mpdamage { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3)); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,3)); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { MOB E=(MOB)newTarget; int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); if((dmg>=E.curState().getHitPoints())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.curState().getHitPoints()-1; if(dmg>0) CMLib.combat().postDamage(E,E,null,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,null); } } else if(newTarget instanceof Item) { Item E=(Item)newTarget; int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); boolean destroy=false; if(E.subjectToWearAndTear()) { if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.usesRemaining()-1; if(dmg>0) E.setUsesRemaining(E.usesRemaining()-dmg); if(E.usesRemaining()<=0) destroy=true; } else if(arg4.equalsIgnoreCase("kill")) destroy=true; if(destroy) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,E.name()+" is destroyed!"); E.destroy(); } } } } break; } case 29: // mptrackto { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,0)); Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1),null,true,0); altStatusTickable=null; } break; } case 53: // mpwalkto { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)); Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0); altStatusTickable=null; } break; } case 21: //MPENDQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.stopQuest(); else scriptableError(scripted,"MPENDQUEST","Unknown","Quest: "+s); break; } case 69: // MPSTEPQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.stepQuest(); else scriptableError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s); break; } case 23: //MPSTARTQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.startQuest(); else scriptableError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s); break; } case 64: //MPLOADQUESTOBJ { String questName=CMParms.getCleanBit(s,1).trim(); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); Quest Q=getQuest(questName); if(Q==null) { scriptableError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName); break; } Object O=Q.getQuestObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2))); if(O==null) { scriptableError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+CMParms.getCleanBit(s,2)+" for Quest: "+questName); break; } String varArg=CMParms.getPastBit(s,2); if((varArg.length()!=2)||(!varArg.startsWith("$"))) { scriptableError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } char c=varArg.charAt(1); if(Character.isDigit(c)) tmp[CMath.s_int(Character.toString(c))]=O; else switch(c) { case 'N': case 'n': if(O instanceof MOB) source=(MOB)O; break; case 'I': case 'i': if(O instanceof Environmental) scripted=(Environmental)O; if(O instanceof MOB) monster=(MOB)O; break; case 'B': case 'b': if(O instanceof Environmental) lastLoaded=(Environmental)O; break; case 'T': case 't': if(O instanceof Environmental) target=(Environmental)O; break; case 'O': case 'o': if(O instanceof Item) primaryItem=(Item)O; break; case 'P': case 'p': if(O instanceof Item) secondaryItem=(Item)O; break; case 'd': case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break; default: scriptableError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } break; } case 22: //MPQUESTWIN { String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(whoName); if(M==null) M=CMLib.map().getPlayer(whoName); if(M!=null) whoName=M.Name(); if(whoName.length()>0) { s=CMParms.getPastBitClean(s,1); Quest Q=getQuest(s); if(Q!=null) Q.declareWinner(whoName); else scriptableError(scripted,"MYQUESTWIN","Unknown","Quest: "+s); } break; } case 24: // MPCALLFUNC { String named=CMParms.getCleanBit(s,1); String parms=CMParms.getPastBit(s,1).trim(); boolean found=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(named)) { found=true; execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) scriptableError(scripted,"MPCALLFUNC","Unknown","Function: "+named); break; } case 27: // MPWHILE { String conditionStr=(s.substring(2).trim()); int x=conditionStr.indexOf("("); if(x<0) { scriptableError(scripted,"MPWHILE","Unknown","Condition: "+s); break; } conditionStr=conditionStr.substring(x+1); x=-1; int depth=0; for(int i=0;i<conditionStr.length();i++) if(conditionStr.charAt(i)=='(') depth++; else if((conditionStr.charAt(i)==')')&&((--depth)<0)) { x=i; break; } if(x<0) { scriptableError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } String cmd2=conditionStr.substring(x+1).trim(); conditionStr=conditionStr.substring(0,x); Vector vscript=new Vector(); vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random()); vscript.addElement(cmd2); long time=System.currentTimeMillis(); while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,conditionStr))&&((System.currentTimeMillis()-time)<4000)) execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp); if((System.currentTimeMillis()-time)>=4000) { scriptableError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+conditionStr); break; } break; } case 26: // MPALARM { String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String parms=CMParms.getPastBit(s,1).trim(); if(CMath.s_int(time.trim())<=0) { scriptableError(scripted,"MPALARM","Syntax","Bad time "+time); break; } if(parms.length()==0) { scriptableError(scripted,"MPALARM","Syntax","No command!"); break; } Vector vscript=new Vector(); vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random()); vscript.addElement(parms); que.insertElementAt(new ScriptableResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg),0); break; } case 37: // mpenable { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3)); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,3)); Ability A=null; if(cast!=null) { if(newTarget instanceof MOB) A=((MOB)newTarget).fetchAbility(cast); if(A==null) A=CMClass.getAbility(cast); if(A==null) { ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if(D==null) scriptableError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast); else if((newTarget!=null)&&(newTarget instanceof MOB)) ((MOB)newTarget).addExpertise(D.ID); } } if((newTarget!=null) &&(A!=null) &&(newTarget instanceof MOB)) { if(!((MOB)newTarget).isMonster()) Log.sysOut("Scriptable",newTarget.Name()+" was MPENABLED with "+A.Name()); if(p2.trim().startsWith("++")) p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency()); else if(p2.trim().startsWith("--")) p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2))); A.setProficiency(CMath.s_int(p2.trim())); A.setMiscText(m2); if(((MOB)newTarget).fetchAbility(A.ID())==null) ((MOB)newTarget).addAbility(A); } break; } case 38: // mpdisable { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if((newTarget!=null)&&(newTarget instanceof MOB)) { Ability A=((MOB)newTarget).findAbility(cast); if(A!=null)((MOB)newTarget).delAbility(A); if((!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scriptable",newTarget.Name()+" was MPDISABLED with "+A.Name()); ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if((newTarget instanceof MOB)&&(D!=null)) ((MOB)newTarget).delExpertise(D.ID); } break; } default: if(cmd.length()>0) { Vector V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); if(V.size()>0) monster.doCommand(V); } break; } } tickStatus=Tickable.STATUS_END; return null; } protected static final Vector empty=new Vector(); protected Vector getScripts() { if(CMSecurity.isDisabled("SCRIPTABLE")) return empty; Vector scripts=null; if(getParms().length()>100) scripts=(Vector)Resources.getResource("PARSEDPRG: "+getParms().substring(0,100)+getParms().length()+getParms().hashCode()); else scripts=(Vector)Resources.getResource("PARSEDPRG: "+getParms()); if(scripts==null) { String script=getParms(); script=CMStrings.replaceAll(script,"`","'"); scripts=parseScripts(script); if(getParms().length()>100) Resources.submitResource("PARSEDPRG: "+getParms().substring(0,100)+getParms().length()+getParms().hashCode(),scripts); else Resources.submitResource("PARSEDPRG: "+getParms(),scripts); } return scripts; } public boolean match(String str, String patt) { if(patt.trim().equalsIgnoreCase("ALL")) return true; if(patt.length()==0) return true; if(str.length()==0) return false; if(str.equalsIgnoreCase(patt)) return true; return false; } private Item makeCheapItem(Environmental E) { Item product=null; if(E instanceof Item) product=(Item)E; else { product=CMClass.getItem("StdItem"); product.setName(E.Name()); product.setDisplayText(E.displayText()); product.setDescription(E.description()); product.setBaseEnvStats((EnvStats)E.baseEnvStats().copyOf()); product.recoverEnvStats(); } return product; } public boolean okMessage(Environmental affecting, CMMsg msg) { if(!super.okMessage(affecting,msg)) return false; if((affecting==null)||(msg.source()==null)) return true; Vector scripts=getScripts(); Vector script=null; boolean tryIt=false; String trigger=null; int triggerCode=0; String str=null; for(int v=0;v<scripts.size();v++) { tryIt=false; script=(Vector)scripts.elementAt(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0)).toUpperCase().trim(); triggerCode=getTriggerCode(trigger); switch(triggerCode) { case 42: // cnclmsg_prog if(canTrigger(42)) { trigger=trigger.substring(12).trim(); String command=CMParms.getCleanBit(trigger,0).toUpperCase().trim(); if(msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command)) { trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); str=""; if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" "; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) tryIt=true; } else if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) tryIt=true; else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=(t.trim()+" "+str.trim()).trim(); tryIt=true; break; } } } } } break; } if(tryIt) { MOB monster=getScriptableMOB(affecting); if(lastKnownLocation==null) lastKnownLocation=msg.source().location(); if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return true; Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; String resp=null; if(msg.target() instanceof MOB) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[12]); else if(msg.target() instanceof Item) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,new Object[12]); else resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[12]); if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL"))) return false; } } return true; } public void executeMsg(Environmental affecting, CMMsg msg) { super.executeMsg(affecting,msg); if((affecting==null)||(msg.source()==null)) return; MOB monster=getScriptableMOB(affecting); if(lastKnownLocation==null) lastKnownLocation=msg.source().location(); if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return; Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; MOB eventMob=monster; if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB)) eventMob=(MOB)defaultItem.owner(); Vector scripts=getScripts(); if(msg.amITarget(eventMob) &&(!msg.amISource(monster)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.source()!=monster)) lastToHurtMe=msg.source(); Vector script=null; for(int v=0;v<scripts.size();v++) { script=(Vector)scripts.elementAt(v); if(script.size()<1) continue; String trigger=((String)script.elementAt(0)).toUpperCase().trim(); int triggerCode=getTriggerCode(trigger); int targetMinorTrigger=-1; switch(triggerCode) { case 1: // greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&canTrigger(1) &&((!(affecting instanceof MOB))||CMLib.flags().canSenseMoving(msg.source(),(MOB)affecting))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 2: // all_greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canActAtAll(monster))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 3: // speech_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3) &&(!msg.amISource(monster)) &&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE))) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { String str=null; if(msg.othersMessage()!=null) str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()),"`","'"); else str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()),"`","'"); str=(" "+str+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); trigger=trigger.substring(11).trim(); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str)); return; } else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i); int x=str.indexOf(" "+t+" "); if(x>=0) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim())); return; } } } } break; case 4: // give_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(4) &&((msg.amITarget(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.tool() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if((trigger.equalsIgnoreCase(msg.tool().Name())) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } } } break; case 40: // llook_prog if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40) &&((msg.amITarget(affecting))||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(10).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 41: // execmsg_prog if(canTrigger(41)) { trigger=trigger.substring(12).trim(); String command=CMParms.getCleanBit(trigger,0).toUpperCase().trim(); if(msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command)) { trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); String str=""; if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" "; boolean doIt=false; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) doIt=true; } else if(trigger.trim().equalsIgnoreCase("ALL")||(trigger.trim().length()==0)) doIt=true; else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=(t.trim()+" "+str.trim()).trim(); doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); return; } } } break; case 39: // look_prog if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39) &&((msg.amITarget(affecting))||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 20: // get_prog if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 22: // drop_prog if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 24: // remove_prog if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(11).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 34: // open_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_OPEN; case 35: // close_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_CLOSE; case 36: // lock_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_LOCK; case 37: // unlock_prog { if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_UNLOCK; if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { switch(triggerCode) { case 34: case 36: trigger=trigger.substring(9).trim(); break; case 35: trigger=trigger.substring(10).trim(); break; case 37: trigger=trigger.substring(11).trim(); break; } Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,null)); return; } } } } break; } case 25: // consume_prog if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(25) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(12).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 21: // put_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); return; } } } } break; case 27: // buy_prog if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27) &&((!(affecting instanceof ShopKeeper)) ||msg.amITarget(affecting)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } } } break; case 28: // sell_prog if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28) &&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper))) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } } } break; case 23: // wear_prog if(((msg.targetMinor()==CMMsg.TYP_WEAR) ||(msg.targetMinor()==CMMsg.TYP_HOLD) ||(msg.targetMinor()==CMMsg.TYP_WIELD)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(23) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 19: // bribe_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.amITarget(eventMob)||(!(affecting instanceof MOB))) &&(!msg.amISource(monster))&&canTrigger(19) &&(msg.tool() instanceof Coins) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(10).trim(); if(trigger.toUpperCase().startsWith("ANY")||trigger.toUpperCase().startsWith("ALL")) trigger=trigger.substring(3).trim(); else if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster))) break; double t=0.0; if(CMath.isDouble(trigger.trim())) t=CMath.s_double(trigger.trim()); else t=new Integer(CMath.s_int(trigger.trim())).doubleValue(); if((((Coins)msg.tool()).getTotalValue()>=t) ||(trigger.equalsIgnoreCase("ALL")) ||(trigger.equalsIgnoreCase("ANY"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } break; case 8: // entry_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8) &&(msg.amISource(eventMob) ||(msg.target()==affecting) ||(msg.tool()==affecting) ||(affecting instanceof Item)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 9: // exit prog if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 10: // death prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10) &&(msg.amISource(eventMob)||(!(affecting instanceof MOB)))) { MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[12]); return; } break; case 44: // kill prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44) &&((msg.tool()==affecting)||(!(affecting instanceof MOB)))) { MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[12]); return; } break; case 26: // damage prog if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26) &&(msg.amITarget(eventMob)||(msg.tool()==affecting))) { Item I=null; if(msg.tool() instanceof Item) I=(Item)msg.tool(); execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),new Object[12]); return; } break; case 29: // login_prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_LOGIN))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN); registeredSpecialEvents.add(new Integer(CMMsg.TYP_LOGIN)); } if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 32: // level_prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_LEVEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL); registeredSpecialEvents.add(new Integer(CMMsg.TYP_LEVEL)); } if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 30: // logoff_prog if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 12: // mask_prog if(!canTrigger(12)) break; case 18: // act_prog if((msg.amISource(monster)) ||((triggerCode==18)&&(!canTrigger(18)))) break; case 43: // imask_prog if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43))) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); str=CMStrings.removeColors(str); str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" "; trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) doIt=true; else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) doIt=true; } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=t; doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; case 38: // social prog if(!msg.amISource(monster) &&canTrigger(38) &&(msg.tool() instanceof Social)) { trigger=CMParms.getPastBit(trigger.trim(),0); if(((Social)msg.tool()).Name().toUpperCase().startsWith(trigger.toUpperCase())) { Item Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name())); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,msg.tool().Name())); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,msg.tool().Name())); return; } } break; case 33: // channel prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_CHANNEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL); registeredSpecialEvents.add(new Integer(CMMsg.TYP_CHANNEL)); } if(!msg.amISource(monster) &&(CMath.bset(msg.othersMajor(),CMMsg.MASK_CHANNEL)) &&canTrigger(33)) { boolean doIt=false; String channel=CMParms.getBit(trigger.trim(),1); int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL; String str=null; if(channel.equalsIgnoreCase(CMLib.channels().getChannelName(channelInt))) { str=msg.sourceMessage(); if(str==null) str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim(); int dex=str.indexOf("["+channel+"]"); if(dex>0) str=str.substring(dex+2+channel.length()).trim(); else { dex=str.indexOf("'"); int edex=str.lastIndexOf("'"); if(edex>dex) str=str.substring(dex+1,edex); } str=" "+CMStrings.removeColors(str)+" "; str=CMStrings.replaceAll(str,"\n\r"," "); trigger=CMParms.getPastBit(trigger.trim(),1); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) doIt=true; else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(match(str.trim(),trigger)) doIt=true; } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=t; doIt=true; break; } } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; case 31: // regmask prog if(!msg.amISource(monster)&&canTrigger(31)) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); trigger=CMParms.getPastBit(trigger.trim(),0); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) doIt=str.trim().equals(trigger.substring(1).trim()); else { Pattern P=(Pattern)patterns.get(trigger); if(P==null) { P=Pattern.compile(trigger, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); patterns.put(trigger,P); } Matcher M=P.matcher(str); doIt=M.find(); if(doIt) str=str.substring(M.start()).trim(); } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; } } } protected int getTriggerCode(String trigger) { int x=trigger.indexOf(" "); Integer I=null; if(x<0) I=(Integer)progH.get(trigger.toUpperCase().trim()); else I=(Integer)progH.get(trigger.substring(0,x).toUpperCase().trim()); if(I==null) return 0; return I.intValue(); } public MOB backupMOB=null; public MOB getScriptableMOB(Tickable ticking) { MOB mob=null; if(ticking instanceof MOB) { mob=(MOB)ticking; if(!mob.amDead()) lastKnownLocation=mob.location(); } else if(ticking instanceof Environmental) { Room R=CMLib.map().roomLocation((Environmental)ticking); if(R!=null) lastKnownLocation=R; if((backupMOB==null)||(backupMOB.amDestroyed())||(backupMOB.amDead())) { backupMOB=CMClass.getMOB("StdMOB"); if(backupMOB!=null) { backupMOB.setName(ticking.name()); backupMOB.setDisplayText(ticking.name()+" is here."); backupMOB.setDescription(""); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } else { mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } return mob; } public boolean canTrigger(int triggerCode) { Long L=(Long)noTrigger.get(new Integer(triggerCode)); if(L==null) return true; if(System.currentTimeMillis()<L.longValue()) return false; noTrigger.remove(new Integer(triggerCode)); return true; } public boolean tick(Tickable ticking, int tickID) { super.tick(ticking,tickID); if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSTARTED)) return false; MOB mob=getScriptableMOB(ticking); Item defaultItem=(ticking instanceof Item)?(Item)ticking:null; if((mob==null)||(lastKnownLocation==null)) { altStatusTickable=null; return true; } Environmental affecting=(ticking instanceof Environmental)?((Environmental)ticking):null; Vector scripts=getScripts(); int triggerCode=-1; for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++) { Vector script=(Vector)scripts.elementAt(thisScriptIndex); String trigger=""; if(script.size()>0) trigger=((String)script.elementAt(0)).toUpperCase().trim(); triggerCode=getTriggerCode(trigger); tickStatus=Tickable.STATUS_BEHAVIOR+triggerCode; switch(triggerCode) { case 5: // rand_Prog if((!mob.amDead())&&canTrigger(5)) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); } break; case 16: // delay_prog if((!mob.amDead())&&canTrigger(16)) { int targetTick=-1; if(delayTargetTimes.containsKey(new Integer(thisScriptIndex))) targetTick=((Integer)delayTargetTimes.get(new Integer(thisScriptIndex))).intValue(); else { int low=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); int high=CMath.s_int(CMParms.getCleanBit(trigger,2).trim()); if(high<low) high=low; targetTick=CMLib.dice().roll(1,high-low+1,low-1); delayTargetTimes.put(new Integer(thisScriptIndex),new Integer(targetTick)); } int delayProgCounter=0; if(delayProgCounters.containsKey(new Integer(thisScriptIndex))) delayProgCounter=((Integer)delayProgCounters.get(new Integer(thisScriptIndex))).intValue(); else delayProgCounters.put(new Integer(thisScriptIndex),new Integer(0)); if(delayProgCounter==targetTick) { execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); delayProgCounter=-1; } delayProgCounters.remove(new Integer(thisScriptIndex)); delayProgCounters.put(new Integer(thisScriptIndex),new Integer(delayProgCounter+1)); } break; case 7: // fightProg if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7)) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[12]); } else if((ticking instanceof Item) &&canTrigger(7) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[12]); } } break; case 11: // hitprcnt if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11)) { int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),mob.maxState().getHitPoints())); if(mob.curState().getHitPoints()<=floor) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[12]); } else if((ticking instanceof Item) &&canTrigger(11) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) { int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),M.maxState().getHitPoints())); if(M.curState().getHitPoints()<=floor) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[12]); } } break; case 6: // once_prog if(!oncesDone.contains(script)&&canTrigger(6)) { oncesDone.addElement(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); } break; case 14: // time_prog if((mob.location()!=null) &&canTrigger(14) &&(!mob.amDead())) { int lastTimeProgDone=-1; if(lastTimeProgsDone.containsKey(new Integer(thisScriptIndex))) lastTimeProgDone=((Integer)lastTimeProgsDone.get(new Integer(thisScriptIndex))).intValue(); int time=mob.location().getArea().getTimeObj().getTimeOfDay(); if(lastTimeProgDone!=time) { boolean done=false; for(int i=1;i<CMParms.numBits(trigger);i++) { if(time==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); lastTimeProgsDone.remove(new Integer(thisScriptIndex)); lastTimeProgsDone.put(new Integer(thisScriptIndex),new Integer(time)); break; } } if(!done) lastTimeProgsDone.remove(new Integer(thisScriptIndex)); } } break; case 15: // day_prog if((mob.location()!=null)&&canTrigger(15) &&(!mob.amDead())) { int lastDayProgDone=-1; if(lastDayProgsDone.containsKey(new Integer(thisScriptIndex))) lastDayProgDone=((Integer)lastDayProgsDone.get(new Integer(thisScriptIndex))).intValue(); int day=mob.location().getArea().getTimeObj().getDayOfMonth(); if(lastDayProgDone!=day) { boolean done=false; for(int i=1;i<CMParms.numBits(trigger);i++) { if(day==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); lastDayProgsDone.remove(new Integer(thisScriptIndex)); lastDayProgsDone.put(new Integer(thisScriptIndex),new Integer(day)); break; } } if(!done) lastDayProgsDone.remove(new Integer(thisScriptIndex)); } } break; case 13: // quest time prog if(!oncesDone.contains(script)&&canTrigger(13)) { Quest Q=getQuest(CMParms.getCleanBit(trigger,1)); if((Q!=null)&&(Q.running())&&(!Q.stopping())) { int time=CMath.s_int(CMParms.getCleanBit(trigger,2).trim()); if(time>=Q.minsRemaining()) { oncesDone.addElement(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); } } } break; default: break; } } tickStatus=Tickable.STATUS_BEHAVIOR+100; dequeResponses(); altStatusTickable=null; return true; } public void dequeResponses() { try{ tickStatus=Tickable.STATUS_BEHAVIOR+100; for(int q=que.size()-1;q>=0;q--) { ScriptableResponse SB=null; try{SB=(ScriptableResponse)que.elementAt(q);}catch(ArrayIndexOutOfBoundsException x){continue;} if(SB.checkTimeToExecute()) { execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,new Object[12]); que.removeElement(SB); } } }catch(Exception e){Log.errOut("Scriptable",e);} } }
com/planet_ink/coffee_mud/Behaviors/Scriptable.java
package com.planet_ink.coffee_mud.Behaviors; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import org.mozilla.javascript.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.planet_ink.coffee_mud.Libraries.interfaces.*; /* Copyright 2000-2007 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Scriptable extends StdBehavior implements ScriptingEngine { public String ID(){return "Scriptable";} protected int canImproveCode(){return Behavior.CAN_MOBS|Behavior.CAN_ITEMS|Behavior.CAN_ROOMS;} protected MOB lastToHurtMe=null; protected Room lastKnownLocation=null; protected Tickable altStatusTickable=null; protected Vector que=new Vector(); protected static final Hashtable funcH=new Hashtable(); protected static final Hashtable methH=new Hashtable(); protected static final Hashtable progH=new Hashtable(); private static Hashtable patterns=new Hashtable(); protected Vector oncesDone=new Vector(); protected Hashtable delayTargetTimes=new Hashtable(); protected Hashtable delayProgCounters=new Hashtable(); protected Hashtable lastTimeProgsDone=new Hashtable(); protected Hashtable lastDayProgsDone=new Hashtable(); private HashSet registeredSpecialEvents=new HashSet(); private Hashtable noTrigger=new Hashtable(); protected long tickStatus=Tickable.STATUS_NOT; private Quest defaultQuest=null; protected CMMsg lastMsg=null; protected Environmental lastLoaded=null; protected static HashSet SIGNS=CMParms.makeHashSet(CMParms.parseCommas("==,>=,>,<,<=,=>,=<,!=",true)); private Quest getQuest(String named) { if((defaultQuest!=null)&&(named.equals("*")||named.equalsIgnoreCase(defaultQuest.name()))) return defaultQuest; Quest Q=null; for(int i=0;i<CMLib.quests().numQuests();i++) { try{Q=CMLib.quests().fetchQuest(i);}catch(Exception e){} if(Q!=null) { if(Q.name().equalsIgnoreCase(named)) if(Q.running()) return Q; } } return CMLib.quests().fetchQuest(named); } public long getTickStatus() { Tickable T=altStatusTickable; if(T!=null) return T.getTickStatus(); return tickStatus; } public void registerDefaultQuest(Quest Q){ defaultQuest=Q; } public boolean endQuest(Environmental hostObj, MOB mob, String quest) { if(mob!=null) { Vector scripts=getScripts(); if(!mob.amDead()) lastKnownLocation=mob.location(); for(int v=0;v<scripts.size();v++) { Vector script=(Vector)scripts.elementAt(v); String trigger=""; if(script.size()>0) trigger=((String)script.elementAt(0)).toUpperCase().trim(); if((getTriggerCode(trigger)==13) //questtimeprog &&(!oncesDone.contains(script)) &&(CMParms.getCleanBit(trigger,1).equalsIgnoreCase(quest)||(quest.equalsIgnoreCase("*"))) &&(CMath.s_int(CMParms.getCleanBit(trigger,2).trim())<0)) { oncesDone.addElement(script); execute(hostObj,mob,mob,mob,null,null,script,null,new Object[10]); return true; } } } return false; } public Vector externalFiles() { Vector xmlfiles=new Vector(); parseParmFilenames(getParms(),xmlfiles,0); return xmlfiles; } public String getVarHost(Environmental E, String rawHost, MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { if(!rawHost.equals("*")) { if(E==null) rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost); else if(E instanceof Room) rawHost=CMLib.map().getExtendedRoomID((Room)E); else rawHost=E.Name(); } return rawHost; } public String getVar(Environmental E, String rawHost, String var, MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var); } public static String getVar(String host, String var) { Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+host); String val=""; if(H!=null) { val=(String)H.get(var.toUpperCase()); if(val==null) val=""; } return val; } private StringBuffer getResourceFileData(String named) { if(getQuest("*")!=null) return getQuest("*").getResourceFileData(named); return new CMFile(Resources.makeFileResourceName(named),null,true).text(); } protected static class JScriptEvent extends ScriptableObject { public String getClassName(){ return "JScriptEvent";} static final long serialVersionUID=43; Environmental h=null; MOB s=null; Environmental t=null; MOB m=null; Item pi=null; Item si=null; Vector scr; String message=null; public Environmental host(){return h;} public MOB source(){return s;} public Environmental target(){return t;} public MOB monster(){return m;} public Item item(){return pi;} public Item item2(){return si;} public String message(){return message;} public void setVar(String host, String var, String value) { Scriptable.mpsetvar(host.toString(),var.toString().toUpperCase(),value.toString()); } public String getVar(String host, String var) { return Scriptable.getVar(host,var);} public String toJavaString(Object O){return Context.toString(O);} public JScriptEvent(Environmental host, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg) { h=host; s=source; t=target; m=monster; pi=primaryItem; si=secondaryItem; message=msg; } } public void setParms(String newParms) { newParms=CMStrings.replaceAll(newParms,"'","`"); if(newParms.startsWith("+")) { String superParms=super.getParms(); if(superParms.length()>100) Resources.removeResource("PARSEDPRG: "+superParms.substring(0,100)+superParms.length()+superParms.hashCode()); else Resources.removeResource("PARSEDPRG: "+superParms); newParms=super.getParms()+";"+newParms.substring(1); } que=new Vector(); oncesDone=new Vector(); delayTargetTimes=new Hashtable(); delayProgCounters=new Hashtable(); lastTimeProgsDone=new Hashtable(); lastDayProgsDone=new Hashtable(); registeredSpecialEvents=new HashSet(); noTrigger=new Hashtable(); super.setParms(newParms); if(oncesDone.size()>0) oncesDone.clear(); } protected void parseParmFilenames(String parse, Vector filenames, int depth) { if(depth>10) return; // no including off to infinity while(parse.length()>0) { int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { if(parse.substring(0,y).trim().endsWith("#")) { parse=parse.substring(y+1); continue; } int z=parse.indexOf("~",y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf("~",z+1); if(z>0) { String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); filenames.addElement(filename); parseParmFilenames(getResourceFileData(filename).toString(),filenames,depth+1); } else { String filename=parse.substring(y+5).trim(); filenames.addElement(filename); parseParmFilenames(getResourceFileData(filename).toString(),filenames,depth+1); break; } } else break; } } protected String parseLoads(String text, int depth) { StringBuffer results=new StringBuffer(""); String parse=text; if(depth>10) return ""; // no including off to infinity String p=null; while(parse.length()>0) { int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { p=parse.substring(0,y).trim(); if((!p.endsWith(";")) &&(!p.endsWith("\n")) &&(!p.endsWith("\r")) &&(p.length()>0)) { results.append(parse.substring(0,y+1)); parse=parse.substring(y+1); continue; } results.append(p+"\n"); int z=parse.indexOf("~",y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf("~",z+1); if(z>0) { String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); results.append(parseLoads(getResourceFileData(filename).toString(),depth+1)); } else { String filename=parse.substring(y+5).trim(); results.append(parseLoads(getResourceFileData(filename).toString(),depth+1)); break; } } else { results.append(parse); break; } } return results.toString(); } protected Vector parseScripts(String text) { synchronized(funcH) { if(funcH.size()==0) { for(int i=0;i<funcs.length;i++) funcH.put(funcs[i],new Integer(i+1)); for(int i=0;i<methods.length;i++) methH.put(methods[i],new Integer(i+1)); for(int i=0;i<progs.length;i++) progH.put(progs[i],new Integer(i+1)); } } Vector V=new Vector(); text=parseLoads(text,0); int y=0; while((text!=null)&&(text.length()>0)) { y=text.indexOf("~"); while((y>0)&&(text.charAt(y-1)=='\\')) y=text.indexOf("~",y+1); String script=""; if(y<0) { script=text.trim(); text=""; } else { script=text.substring(0,y).trim(); text=text.substring(y+1).trim(); } if(script.length()>0) V.addElement(script); } for(int v=0;v<V.size();v++) { String s=(String)V.elementAt(v); Vector script=new Vector(); while(s.length()>0) { y=-1; int yy=0; while(yy<s.length()) if((s.charAt(yy)==';')&&((yy<=0)||(s.charAt(yy-1)!='\\'))) {y=yy;break;} else if(s.charAt(yy)=='\n'){y=yy;break;} else if(s.charAt(yy)=='\r'){y=yy;break;} else yy++; String cmd=""; if(y<0) { cmd=s.trim(); s=""; } else { cmd=s.substring(0,y).trim(); s=s.substring(y+1).trim(); } if((cmd.length()>0)&&(!cmd.startsWith("#"))) { cmd=CMStrings.replaceAll(cmd,"\\~","~"); cmd=CMStrings.replaceAll(cmd,"\\=","="); script.addElement(CMStrings.replaceAll(cmd,"\\;",";")); } } V.setElementAt(script,v); } V.trimToSize(); return V; } protected Room getRoom(String thisName, Room imHere) { if(thisName.length()==0) return null; Room room=CMLib.map().getRoom(thisName); if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName))) return room; Room inAreaRoom=null; try { for(Enumeration p=CMLib.map().players();p.hasMoreElements();) { MOB M=(MOB)p.nextElement(); if((M.Name().equalsIgnoreCase(thisName)) &&(M.location()!=null) &&(CMLib.flags().isInTheGame(M,true))) inAreaRoom=M.location(); } if(inAreaRoom==null) for(Enumeration p=CMLib.map().players();p.hasMoreElements();) { MOB M=(MOB)p.nextElement(); if((M.name().equalsIgnoreCase(thisName)) &&(M.location()!=null) &&(CMLib.flags().isInTheGame(M,true))) inAreaRoom=M.location(); } if(inAreaRoom==null) for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if((R.roomID().endsWith("#"+thisName)) ||(R.roomID().endsWith(thisName))) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if(CMLib.english().containsString(R.displayText(),thisName)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if(CMLib.english().containsString(R.description(),thisName)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; if(room!=null) return room; try { for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); if((R.fetchInhabitant(thisName)!=null) ||(R.fetchItem(null,thisName)!=null)) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) inAreaRoom=R; else room=R; } } }catch(NoSuchElementException nse){} if(inAreaRoom!=null) return inAreaRoom; return room; } protected void scriptableError(Environmental scripted, String cmdName, String errType, String errMsg) { if(scripted!=null) { Room R=CMLib.map().roomLocation(scripted); Log.errOut("Scriptable",scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg); if(R!=null) R.showHappens(CMMsg.MSG_OK_VISUAL,"Scriptable Error: "+scripted.name()+"/"+CMLib.map().getExtendedRoomID(R)+"/"+CMParms.toStringList(externalFiles())+"/"+ cmdName+"/"+errType+"/"+errMsg); } else Log.errOut("Scriptable","*/*/"+CMParms.toStringList(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg); } protected boolean simpleEvalStr(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { int x=arg1.compareToIgnoreCase(arg2); if(cmp.equalsIgnoreCase("==")) return (x==0); else if(cmp.equalsIgnoreCase(">=")) return (x==0)||(x>0); else if(cmp.equalsIgnoreCase("<=")) return (x==0)||(x<0); else if(cmp.equalsIgnoreCase(">")) return (x>0); else if(cmp.equalsIgnoreCase("<")) return (x<0); else if(cmp.equalsIgnoreCase("!=")) return (x!=0); else { scriptableError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2); return false; } } protected boolean simpleEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { long val1=CMath.s_long(arg1.trim()); long val2=CMath.s_long(arg2.trim()); if(cmp.equalsIgnoreCase("==")) return (val1==val2); else if(cmp.equalsIgnoreCase(">=")) return val1>=val2; else if(cmp.equalsIgnoreCase("<=")) return val1<=val2; else if(cmp.equalsIgnoreCase(">")) return (val1>val2); else if(cmp.equalsIgnoreCase("<")) return (val1<val2); else if(cmp.equalsIgnoreCase("!=")) return (val1!=val2); else { scriptableError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } } protected boolean simpleExpressionEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { double val1=CMath.s_parseMathExpression(arg1.trim()); double val2=CMath.s_parseMathExpression(arg2.trim()); if(cmp.equalsIgnoreCase("==")) return (val1==val2); else if(cmp.equalsIgnoreCase(">=")) return val1>=val2; else if(cmp.equalsIgnoreCase("<=")) return val1<=val2; else if(cmp.equalsIgnoreCase(">")) return (val1>val2); else if(cmp.equalsIgnoreCase("<")) return (val1<val2); else if(cmp.equalsIgnoreCase("!=")) return (val1!=val2); else { scriptableError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } } protected Vector loadMobsFromFile(Environmental scripted, String filename) { filename=filename.trim(); Vector monsters=(Vector)Resources.getResource("RANDOMMONSTERS-"+filename); if(monsters!=null) return monsters; StringBuffer buf=getResourceFileData(filename); String thangName="null"; Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { scriptableError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } if(buf.substring(0,20).indexOf("<MOBS>")<0) { scriptableError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } monsters=new Vector(); String error=CMLib.coffeeMaker().addMOBsFromXML(buf.toString(),monsters,null); if(error.length()>0) { scriptableError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(monsters.size()<=0) { scriptableError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMMONSTERS-"+filename,monsters); return monsters; } protected Vector loadItemsFromFile(Environmental scripted, String filename) { filename=filename.trim(); Vector items=(Vector)Resources.getResource("RANDOMITEMS-"+filename); if(items!=null) return items; StringBuffer buf=getResourceFileData(filename); String thangName="null"; Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { scriptableError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } if(buf.substring(0,20).indexOf("<ITEMS>")<0) { scriptableError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } items=new Vector(); String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null); if(error.length()>0) { scriptableError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(items.size()<=0) { scriptableError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMITEMS-"+filename,items); return items; } protected Environmental findSomethingCalledThis(String thisName, MOB meMOB, Room imHere, Vector OBJS, boolean mob) { if(thisName.length()==0) return null; Environmental thing=null; Environmental areaThing=null; ShopKeeper SK=null; if(thisName.toUpperCase().trim().startsWith("FROMFILE ")) { try{ Vector V=null; if(mob) V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1)); else V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1)); if(V!=null) { String name=CMParms.getPastBit(thisName,1); if(name.equalsIgnoreCase("ALL")) OBJS=V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=(Environmental)V.elementAt(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(Exception e){} } else { if(!mob) areaThing=(meMOB!=null)?meMOB.fetchInventory(thisName):null; try { if(areaThing==null) for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();) { Room R=(Room)r.nextElement(); Environmental E=null; if(mob) E=R.fetchInhabitant(thisName); else { E=R.fetchItem(null,thisName); if(E==null) for(int i=0;i<R.numInhabitants();i++) { MOB M=R.fetchInhabitant(i); if(M!=null) { E=M.fetchInventory(thisName); SK=CMLib.coffeeShops().getShopKeeper(M); if((SK!=null)&&(E==null)) E=SK.getShop().getStock(thisName,null,SK.whatIsSold(),M.getStartRoom()); } } } if(E!=null) { if((imHere!=null)&&(imHere.getArea().Name().equals(R.getArea().Name()))) areaThing=E; else thing=E; } } }catch(NoSuchElementException nse){} } if(areaThing!=null) OBJS.addElement(areaThing); else if(thing!=null) OBJS.addElement(thing); if(OBJS.size()>0) return (Environmental)OBJS.firstElement(); return null; } public Environmental getArgumentMOB(String str, MOB source, MOB monster, Environmental target, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); } public Environmental getArgumentItem(String str, MOB source, MOB monster, Environmental scripted, Environmental target, Item primaryItem, Item secondaryItem, String msg, Object[] tmp) { if(str.length()<2) return null; if(str.charAt(0)=='$') { if(Character.isDigit(str.charAt(1))) { Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))]; if(O instanceof Environmental) return (Environmental)O; else if((O instanceof Vector)&&(str.length()>3)&&(str.charAt(2)=='.')) { Vector V=(Vector)O; String back=str.substring(2); if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length())&&(Character.isDigit(back.charAt(x)))) x++; int y=CMath.s_int(back.substring(1,x).trim()); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) return null; O=V.elementAt(y); if(O instanceof Environmental) return (Environmental)O; } str=O.toString(); // will fall through } } else if(O!=null) str=O.toString(); // will fall through else return null; } else switch(str.charAt(1)) { case 'a': return (lastKnownLocation!=null)?lastKnownLocation.getArea():null; case 'B': case 'b': return lastLoaded; case 'N': case 'n': return source; case 'I': case 'i': return scripted; case 'T': case 't': return target; case 'O': case 'o': return primaryItem; case 'P': case 'p': return secondaryItem; case 'd': case 'D': return lastKnownLocation; case 'F': case 'f': if((monster!=null)&&(monster.amFollowing()!=null)) return monster.amFollowing(); return null; case 'r': case 'R': return getFirstPC(monster,null,lastKnownLocation); case 'c': case 'C': return getFirstAnyone(monster,null,lastKnownLocation); case 'w': return primaryItem!=null?primaryItem.owner():null; case 'W': return secondaryItem!=null?secondaryItem.owner():null; case 'x': case 'X': if(lastKnownLocation!=null) { if((str.length()>2)&&(Directions.getGoodDirectionCode(""+str.charAt(2))>=0)) return lastKnownLocation.getExitInDir(Directions.getGoodDirectionCode(""+str.charAt(2))); int i=0; Exit E=null; while(((++i)<100)||(E!=null)) E=lastKnownLocation.getExitInDir(CMLib.dice().roll(1,Directions.NUM_DIRECTIONS,-1)); return E; } return null; case '[': { int x=str.substring(2).indexOf("]"); if(x>=0) { String mid=str.substring(2).substring(0,x); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) return Q.getQuestItem(num); } } } break; case '{': { int x=str.substring(2).indexOf("}"); if(x>=0) { String mid=str.substring(2).substring(0,x).trim(); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) return Q.getQuestMob(num); } } } break; } } if(lastKnownLocation!=null) { str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str); Environmental E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str,Item.WORNREQ_ANY); if(E==null) E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Item.WORNREQ_ANY); if(E==null) E=lastKnownLocation.fetchAnyItem(str); if((E==null)&&(monster!=null)) E=monster.fetchInventory(str); return E; } return null; } private String makeNamedString(Object O) { if(O instanceof Vector) return makeParsableString((Vector)O); else if(O instanceof Room) return ((Room)O).roomTitle(); else if(O instanceof Environmental) return ((Environmental)O).Name(); else if(O!=null) return O.toString(); return ""; } private String makeParsableString(Vector V) { if((V==null)||(V.size()==0)) return ""; if(V.firstElement() instanceof String) return CMParms.combineWithQuotes(V,0); StringBuffer ret=new StringBuffer(""); String S=null; for(int v=0;v<V.size();v++) { S=makeNamedString(V.elementAt(v)).trim(); if(S.length()==0) ret.append("? "); else if(S.indexOf(" ")>=0) ret.append("\""+S+"\" "); else ret.append(S+" "); } return ret.toString(); } public String varify(MOB source, Environmental target, Environmental scripted, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String varifyable) { int t=varifyable.indexOf("$"); if((monster!=null)&&(monster.location()!=null)) lastKnownLocation=monster.location(); if(lastKnownLocation==null) lastKnownLocation=source.location(); MOB randMOB=null; while((t>=0)&&(t<varifyable.length()-1)) { char c=varifyable.charAt(t+1); String middle=""; String front=varifyable.substring(0,t); String back=varifyable.substring(t+2); if(Character.isDigit(c)) middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]); else switch(c) { case '@': if((t<varifyable.length()-2)&&Character.isLetter(varifyable.charAt(t+2))) { Environmental E=getArgumentItem("$"+varifyable.charAt(t+2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); middle=(E==null)?"null":""+E; } break; case 'a': if(lastKnownLocation!=null) middle=lastKnownLocation.getArea().name(); break; case 'b': middle=lastLoaded!=null?lastLoaded.name():""; break; case 'B': middle=lastLoaded!=null?lastLoaded.displayText():""; break; case 'c': case 'C': randMOB=getFirstAnyone(monster,randMOB,lastKnownLocation); if(randMOB!=null) middle=randMOB.name(); break; case 'i': if(monster!=null) middle=monster.name(); break; case 'I': if(monster!=null) middle=monster.displayText(); break; case 'n': case 'N': if(source!=null) middle=source.name(); break; case 't': case 'T': if(target!=null) middle=target.name(); break; case 'y': if(source!=null) middle=source.charStats().sirmadam(); break; case 'Y': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().sirmadam(); break; case 'r': case 'R': randMOB=getFirstPC(monster,randMOB,lastKnownLocation); if(randMOB!=null) middle=randMOB.name(); break; case 'j': if(monster!=null) middle=monster.charStats().heshe(); break; case 'f': if((monster!=null)&&(monster.amFollowing()!=null)) middle=monster.amFollowing().name(); break; case 'F': if((monster!=null)&&(monster.amFollowing()!=null)) middle=monster.amFollowing().charStats().heshe(); break; case 'e': if(source!=null) middle=source.charStats().heshe(); break; case 'E': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().heshe(); break; case 'J': randMOB=getFirstPC(monster,randMOB,lastKnownLocation); if(randMOB!=null) middle=randMOB.charStats().heshe(); break; case 'k': if(monster!=null) middle=monster.charStats().hisher(); break; case 'm': if(source!=null) middle=source.charStats().hisher(); break; case 'M': if((target!=null)&&(target instanceof MOB)) middle=((MOB)target).charStats().hisher(); break; case 'K': randMOB=getFirstPC(monster,randMOB,lastKnownLocation); if(randMOB!=null) middle=randMOB.charStats().hisher(); break; case 'o': case 'O': if(primaryItem!=null) middle=primaryItem.name(); break; case 'g': middle=((msg==null)?"":msg.toLowerCase()); break; case 'G': middle=((msg==null)?"":msg); break; case 'd': middle=(lastKnownLocation!=null)?lastKnownLocation.roomTitle():""; break; case 'D': middle=(lastKnownLocation!=null)?lastKnownLocation.roomDescription():""; break; case 'p': case 'P': if(secondaryItem!=null) middle=secondaryItem.name(); break; case 'w': middle=primaryItem!=null?primaryItem.owner().Name():middle; break; case 'W': middle=secondaryItem!=null?secondaryItem.owner().Name():middle; break; case 'l': if(lastKnownLocation!=null) { StringBuffer str=new StringBuffer(""); for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if((M!=null)&&(M!=monster)&&(CMLib.flags().canBeSeenBy(M,monster))) str.append("\""+M.name()+"\" "); } middle=str.toString(); } break; case 'L': if(lastKnownLocation!=null) { StringBuffer str=new StringBuffer(""); for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)&&(CMLib.flags().canBeSeenBy(I,monster))) str.append("\""+I.name()+"\" "); } middle=str.toString(); } break; case '<': { int x=back.indexOf(">"); if(x>=0) { String mid=back.substring(0,x); int y=mid.indexOf(" "); Environmental E=null; String arg1=""; if(y>=0) { arg1=mid.substring(0,y).trim(); E=getArgumentItem(arg1,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); mid=mid.substring(y+1).trim(); } if(arg1.length()>0) middle=getVar(E,arg1,mid,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); back=back.substring(x+1); } } break; case '[': { middle=""; int x=back.indexOf("]"); if(x>=0) { String mid=back.substring(0,x); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) middle=Q.getQuestItemName(num); } back=back.substring(x+1); } } break; case '{': { middle=""; int x=back.indexOf("}"); if(x>=0) { String mid=back.substring(0,x).trim(); int y=mid.indexOf(" "); if(y>0) { int num=CMath.s_int(mid.substring(0,y).trim()); mid=mid.substring(y+1).trim(); Quest Q=getQuest(mid); if(Q!=null) middle=Q.getQuestMobName(num); } back=back.substring(x+1); } } break; case '%': { middle=""; int x=back.indexOf("%"); if(x>=0) { middle=functify(monster,source,target,monster,primaryItem,secondaryItem,msg,tmp,back.substring(0,x).trim()); back=back.substring(x+1); } } break; //case 'a': case 'A': // unnecessary, since, in coffeemud, this is part of the name break; case 'x': case 'X': if(lastKnownLocation!=null) { middle=""; Exit E=null; int dir=-1; if((t<varifyable.length()-2)&&(Directions.getGoodDirectionCode(""+varifyable.charAt(t+2))>=0)) { dir=Directions.getGoodDirectionCode(""+varifyable.charAt(t+2)); E=lastKnownLocation.getExitInDir(dir); } else { int i=0; while(((++i)<100)||(E!=null)) { dir=CMLib.dice().roll(1,Directions.NUM_DIRECTIONS,-1); E=lastKnownLocation.getExitInDir(dir); } } if((dir>=0)&&(E!=null)) { if(c=='x') middle=Directions.getDirectionName(dir); else middle=E.name(); } } break; } if((middle.length()>0) &&(back.startsWith(".")) &&(back.length()>1)) { if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if(back.equalsIgnoreCase("#LENGTH#")) middle=""+CMParms.parse(middle).size(); else if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length()) &&(Character.isDigit(back.charAt(x)))) x++; int y=CMath.s_int(back.substring(1,x).trim()); back=back.substring(x); boolean rest=back.startsWith(".."); if(rest) back=back.substring(2); Vector V=CMParms.parse(middle); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) middle=""; else if(rest) middle=CMParms.combine(V,y); else middle=(String)V.elementAt(y); } } } varifyable=front+middle+back; t=varifyable.indexOf("$"); } return varifyable; } public static DVector getScriptVarSet(String mobname, String varname) { DVector set=new DVector(2); if(mobname.equals("*")) { Vector V=Resources.findResourceKeys("SCRIPTVAR-"); for(int v=0;v<V.size();v++) { String key=(String)V.elementAt(v); if(key.startsWith("SCRIPTVAR-")) { Hashtable H=(Hashtable)Resources.getResource(key); if(varname.equals("*")) { for(Enumeration e=H.keys();e.hasMoreElements();) { String vn=(String)e.nextElement(); set.addElement(key.substring(10),vn); } } else set.addElement(key.substring(10),varname); } } } else { Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+mobname); if(varname.equals("*")) { for(Enumeration e=H.keys();e.hasMoreElements();) { String vn=(String)e.nextElement(); set.addElement(mobname,vn); } } else set.addElement(mobname,varname); } return set; } public String getStatValue(Environmental E, String arg2) { boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if((!found)&&(E instanceof MOB)) { MOB M=(MOB)E; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.STAT_DESCS[i]); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } if(!found) for(int i=0;i<M.envStats().getStatCodes().length;i++) if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.envStats().getStat(M.envStats().getStatCodes()[i]); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } if(!found)return null; return val; } public String getGStatValue(Environmental E, String arg2) { if(E==null) return null; boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if(!found) if(E instanceof MOB) { for(int i=0;i<CMObjectBuilder.GENMOBCODES.length;i++) { if(CMObjectBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2)) { val=CMLib.coffeeMaker().getGenMobStat((MOB)E,CMObjectBuilder.GENMOBCODES[i]); found=true; break; } } if(!found) { MOB M=(MOB)E; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.STAT_DESCS[i]); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } if(!found) for(int i=0;i<M.envStats().getStatCodes().length;i++) if(M.envStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.envStats().getStat(M.envStats().getStatCodes()[i]); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } } else if(E instanceof Item) { for(int i=0;i<CMObjectBuilder.GENITEMCODES.length;i++) { if(CMObjectBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2)) { val=CMLib.coffeeMaker().getGenItemStat((Item)E,CMObjectBuilder.GENITEMCODES[i]); found=true; break; } } } if(found) return val; return null; } public static void mpsetvar(String name, String key, String val) { DVector V=getScriptVarSet(name,key); for(int v=0;v<V.size();v++) { name=(String)V.elementAt(v,1); key=((String)V.elementAt(v,2)).toUpperCase(); Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+name); if(H==null) { if(val.length()==0) continue; H=new Hashtable(); Resources.submitResource("SCRIPTVAR-"+name,H); } if(val.equals("++")) { String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())+1).toString(); } else if(val.equals("--")) { String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())-1).toString(); } else if(val.startsWith("+")) { // add via +number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())+amount).toString(); } else if(val.startsWith("-")) { // subtract -number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())-amount).toString(); } else if(val.startsWith("*")) { // multiply via *number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())*amount).toString(); } else if(val.startsWith("/")) { // divide /number form val=val.substring(1); int amount=CMath.s_int(val.trim()); String num=(String)H.get(key); if(num==null) num="0"; val=new Integer(CMath.s_int(num.trim())/amount).toString(); } if(H.containsKey(key)) H.remove(key); if(val.trim().length()>0) H.put(key,val); if(H.size()==0) Resources.removeResource("SCRIPTVAR-"+name); } } public boolean eval(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String evaluable) { boolean anythingChanged=false; Vector formatCheck=CMParms.parse(evaluable); for(int i=1;i<(formatCheck.size()-1);i++) if((SIGNS.contains(formatCheck.elementAt(i))) &&(((String)formatCheck.elementAt(i-1)).endsWith(")"))) { anythingChanged=true; String ps=(String)formatCheck.elementAt(i-1); ps=ps.substring(0,ps.length()-1); if(ps.length()==0) ps=" "; formatCheck.setElementAt(ps,i-1); String os=null; if((((String)formatCheck.elementAt(i+1)).startsWith("'") ||((String)formatCheck.elementAt(i+1)).startsWith("`"))) { os=""; while((i<(formatCheck.size()-1)) &&((!((String)formatCheck.elementAt(i+1)).endsWith("'")) &&(!((String)formatCheck.elementAt(i+1)).endsWith("`")))) { os+=((String)formatCheck.elementAt(i+1))+" "; formatCheck.removeElementAt(i+1); } os=(os+((String)formatCheck.elementAt(i+1))).trim(); } else if((i==(formatCheck.size()-3)) &&(((String)formatCheck.lastElement()).indexOf("(")<0)) { os=((String)formatCheck.elementAt(i+1)) +" "+((String)formatCheck.elementAt(i+2)); formatCheck.removeElementAt(i+2); } else os=(String)formatCheck.elementAt(i+1); os=os+")"; formatCheck.setElementAt(os,i+1); i+=2; } if(anythingChanged) evaluable=CMParms.combine(formatCheck,0); String uevaluable=evaluable.toUpperCase().trim(); boolean returnable=false; boolean lastreturnable=true; int joined=0; while(evaluable.length()>0) { int y=evaluable.indexOf("("); int z=y+1; int numy=1; while((y>=0)&&(numy>0)&&(z<evaluable.length())) { if(evaluable.charAt(z)=='(') numy++; else if(evaluable.charAt(z)==')') numy--; z++; } if((y<0)||(numy>0)||(z<=y)) { scriptableError(scripted,"EVAL","Format",evaluable); return false; } z--; String preFab=uevaluable.substring(0,y).trim(); Integer funcCode=(Integer)funcH.get(preFab); if(funcCode==null) funcCode=new Integer(0); if(y==0) { int depth=0; int i=0; while((++i)<evaluable.length()) { char c=evaluable.charAt(i); if((c==')')&&(depth==0)) { String expr=evaluable.substring(1,i); evaluable=evaluable.substring(i+1).trim(); uevaluable=uevaluable.substring(i+1).trim(); returnable=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,expr); switch(joined) { case 1: returnable=lastreturnable&&returnable; break; case 2: returnable=lastreturnable||returnable; break; case 4: returnable=!returnable; break; case 5: returnable=lastreturnable&&(!returnable); break; case 6: returnable=lastreturnable||(!returnable); break; default: break; } joined=0; break; } else if(c=='(') depth++; else if(c==')') depth--; } z=evaluable.indexOf(")"); } else if(evaluable.startsWith("!")) { joined=joined|4; evaluable=evaluable.substring(1).trim(); uevaluable=uevaluable.substring(1).trim(); } else if(uevaluable.startsWith("AND ")) { joined=1; lastreturnable=returnable; evaluable=evaluable.substring(4).trim(); uevaluable=uevaluable.substring(4).trim(); } else if(uevaluable.startsWith("OR ")) { joined=2; lastreturnable=returnable; evaluable=evaluable.substring(3).trim(); uevaluable=uevaluable.substring(3).trim(); } else if((y<0)||(z<y)) { scriptableError(scripted,"()","Syntax",evaluable); break; } else { tickStatus=Tickable.STATUS_MISC+funcCode.intValue(); switch(funcCode.intValue()) { case 1: // rand { String num=evaluable.substring(y+1,z).trim(); if(num.endsWith("%")) num=num.substring(0,num.length()-1); int arg=CMath.s_int(num); if(CMLib.dice().rollPercentage()<arg) returnable=true; else returnable=false; break; } case 2: // has { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HAS","Syntax",evaluable); return returnable; } Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(E2!=null) returnable=((MOB)E).isMine(E2); else returnable=(((MOB)E).fetchInventory(arg2)!=null); } else if(E instanceof Item) returnable=CMLib.english().containsString(E.name(),arg2); else if(E instanceof Room) { if(E2 instanceof Item) returnable=((Room)E).isContent((Item)E2); else returnable=(((Room)E).fetchItem(null,arg2)!=null); } else returnable=false; break; } case 74: // hasnum { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((value.length()==0)||(item.length()==0)||(cmp.length()==0)) { scriptableError(scripted,"HASNUM","Syntax",evaluable); return returnable; } Item I=null; int num=0; if(E==null) returnable=false; else if(E instanceof MOB) { MOB M=(MOB)E; for(int i=0;i<M.inventorySize();i++) { I=M.fetchInventory(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Room) { Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.fetchItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else returnable=false; break; } case 67: // hastitle { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HASTITLE","Syntax",evaluable); return returnable; } if(E instanceof MOB) { MOB M=(MOB)E; returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2)); } else returnable=false; break; } case 3: // worn { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"WORN","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else if(E instanceof MOB) returnable=(((MOB)E).fetchWornItem(arg2)!=null); else if(E instanceof Item) returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Item.IN_INVENTORY))); else returnable=false; break; } case 4: // isnpc { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isMonster(); break; } case 87: // isbirthday { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else { MOB mob=(MOB)E; if(mob.playerStats()==null) returnable=false; else { int tage=mob.baseCharStats().getMyRace().getAgingChart()[Race.AGE_YOUNGADULT] +CMClass.globalClock().getYear() -mob.playerStats().getBirthday()[2]; int month=CMClass.globalClock().getMonth(); int day=CMClass.globalClock().getDayOfMonth(); int bday=mob.playerStats().getBirthday()[0]; int bmonth=mob.playerStats().getBirthday()[1]; if((tage>mob.baseCharStats().getStat(CharStats.STAT_AGE)) &&((month==bmonth)&&(day==bday))) returnable=true; else returnable=false; } } break; } case 5: // ispc { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=!((MOB)E).isMonster(); break; } case 6: // isgood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isGood(E); break; } case 8: // isevil { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isEvil(E); break; } case 9: // isneutral { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().isNeutral(E); break; } case 54: // isalive { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) returnable=true; else returnable=false; break; } case 58: // isable { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) returnable=((MOB)E).fetchExpertise(X.ID())!=null; else returnable=((MOB)E).findAbility(arg2)!=null; } else returnable=false; break; } case 59: // isopen { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } break; } case 60: // islocked { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isLocked(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isLocked(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isLocked(); } break; } case 10: // isfight { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isInCombat(); break; } case 11: // isimmort { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,"IMMORT"); break; } case 12: // ischarmed { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0; break; } case 15: // isfollow { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).amFollowing()==null) returnable=false; else if(((MOB)E).amFollowing().location()!=lastKnownLocation) returnable=false; else returnable=true; break; } case 73: // isservant { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0)) returnable=false; else if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null) returnable=false; else returnable=true; break; } case 55: // ispkill { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL)) returnable=true; else returnable=false; break; } case 7: // isname { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.english().containsString(E.name(),arg2); break; } case 56: // name { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME"); break; } case 75: // currency { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY"); break; } case 61: // strin { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Vector V=CMParms.parse(arg1.toUpperCase()); returnable=V.contains(arg2.toUpperCase()); break; } case 62: // callfunc { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); String found=null; boolean validFunc=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) scriptableError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else returnable=!(found.trim().length()==0); break; } case 14: // affected { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=(E.fetchEffect(arg2)!=null); break; } case 69: // isbehave { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=(E.fetchBehavior(arg2)!=null); break; } case 70: // ipaddress { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster())) returnable=false; else returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS"); break; } case 28: // questwinner { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { if(E!=null) arg1=E.Name(); returnable=Q.wasWinner(arg1); } break; } case 29: // questmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.wasQuestMob(arg1)>=0); break; } case 31: // isquestmobalive { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.wasQuestMob(arg1)); if(M==null) returnable=false; else returnable=!M.amDead(); } break; } case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Vector MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA"); break; } case 33: // nummobs { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Vector MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } }catch(NoSuchElementException nse){} returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS"); break; } case 34: // numracesinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; Room R=null; MOB M=null; for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA"); break; } case 35: // numraces { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); int num=0; try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } }catch(NoSuchElementException nse){} returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES"); break; } case 30: // questobj { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.wasQuestItem(arg1)>=0); break; } case 85: // islike { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.masking().maskCheck(arg2, E,false); break; } case 86: // strcontains { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); returnable=CMParms.stringContains(arg1,arg2)>=0; break; } case 92: // isodd { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } returnable = isodd; break; } case 16: // hitprcnt { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"HITPRCNT","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); int val1=(int)Math.round(hitPctD*100.0); returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT"); } break; } case 50: // isseason { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) for(int a=0;a<TimeClock.SEASON_DESCS.length;a++) if((TimeClock.SEASON_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getSeasonCode()==a)) {returnable=true; break;} break; } case 51: // isweather { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) for(int a=0;a<Climate.WEATHER_DESCS.length;a++) if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a)) {returnable=true; break;} break; } case 57: // ismoon { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); returnable=false; if(monster.location()!=null) { if(arg1.length()==0) returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location()); else for(int a=0;a<TimeClock.PHASE_DESC.length;a++) if((TimeClock.PHASE_DESC[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getMoonPhase()==a)) { returnable=true; break; } } break; } case 38: // istime { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(monster.location()==null) returnable=false; else if(("daytime").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAY)) returnable=true; else if(("dawn").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DAWN)) returnable=true; else if(("dusk").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_DUSK)) returnable=true; else if(("nighttime").startsWith(arg1.toLowerCase()) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TIME_NIGHT)) returnable=true; else if((monster.location().getArea().getTimeObj().getTODCode()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 39: // isday { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 45: // nummobsroom { int num=0; int startbit=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); if((CMParms.numBits(evaluable.substring(y+1,z))>2) &&(!CMath.isInteger(CMParms.getCleanBit(evaluable.substring(y+1,z),1).trim()))) { String name=CMParms.getCleanBit(evaluable.substring(y+1,z),0); startbit++; if(!name.equalsIgnoreCase("*")) { num=0; Vector MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } } String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),startbit)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),startbit)); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMMOBSROOM"); break; } case 63: // numpcsroom { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+lastKnownLocation.numPCInhabitants(),arg2,arg1,"NUMPCSROOM"); break; } case 79: // numpcsarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if(lastKnownLocation!=null) { int num=0; for(int s=0;s<CMLib.sessions().size();s++) { Session S=CMLib.sessions().elementAt(s); if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA"); } break; } case 77: // explored { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),2)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) { scriptableError(scripted,"EXPLORED","Unknown Code",whom); return returnable; } Area A=null; if(!where.equalsIgnoreCase("world")) { Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 instanceof Area) A=(Area)E2; else A=CMLib.map().getArea(where); if(A==null) { scriptableError(scripted,"EXPLORED","Unknown Area",where); return returnable; } } if(lastKnownLocation!=null) { int pct=0; MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED"); } break; } case 72: // faction { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),2)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),3)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Faction F=CMLib.factions().getFaction(arg1); if((E==null)||(!(E instanceof MOB))) { scriptableError(scripted,"FACTION","Unknown Code",whom); return returnable; } if(F==null) { scriptableError(scripted,"FACTION","Unknown Faction",arg1); return returnable; } MOB M=(MOB)E; String value=null; if(!M.hasFaction(F.factionID())) value=""; else { int myfac=M.fetchFaction(F.factionID()); if(CMath.isNumber(arg2.trim())) value=new Integer(myfac).toString(); else { Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),myfac); if(FR==null) value=""; else value=FR.name(); } } if(lastKnownLocation!=null) returnable=simpleEval(scripted,value,arg2,cmp,"FACTION"); break; } case 46: // numitemsroom { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) ct++; } returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM"); break; } case 47: //mobitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); Item which=null; int ct=1; if(M!=null) for(int i=0;i<M.inventorySize();i++) { Item I=M.fetchInventory(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which=I; break;} ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); break; } case 49: // hastattoo { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"HASTATTOO","Syntax",evaluable); break; } else if((E!=null)&&(E instanceof MOB)) returnable=(((MOB)E).fetchTattoo(arg2)!=null); else returnable=false; break; } case 48: // numitemsmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); MOB which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); int ct=1; if(which!=null) for(int i=0;i<which.inventorySize();i++) { Item I=which.fetchInventory(i); if((I!=null)&&(I.container()==null)) ct++; } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB"); break; } case 43: // roommob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 44: // roomitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which=I; break;} ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 36: // ishere { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(lastKnownLocation!=null) returnable=((lastKnownLocation.fetchAnyItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null)); else returnable=false; break; } case 17: // inroom { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"INROOM","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM"); } break; } case 90: // inarea { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"INAREA","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA"); } break; } case 89: // isrecall { String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String comp="=="; Environmental E=monster; if((" == >= > < <= => =< != ".indexOf(" "+CMParms.getCleanBit(evaluable.substring(y+1,z),1)+" ")>=0)) { E=getArgumentItem(CMParms.getCleanBit(evaluable.substring(y+1,z),0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=CMParms.getCleanBit(evaluable.substring(y+1,z),1); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); } else { scriptableError(scripted,"ISRECALL","Syntax",evaluable); return returnable; } Room R=null; if(arg2.startsWith("$")) R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { Room R2=CMLib.map().getStartRoom(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL"); } break; } case 37: // inlocale { String parms=evaluable.substring(y+1,z); String arg2=null; Environmental E=monster; if(CMParms.numBits(parms)==1) arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(parms)); else { E=getArgumentItem(CMParms.getCleanBit(parms,0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(parms,0)); } if(E==null) returnable=false; else if(arg2.length()==0) returnable=true; else { Room R=CMLib.map().roomLocation(E); if(R==null) returnable=false; else if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0) returnable=true; else returnable=false; } break; } case 18: // sex { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0).toUpperCase()); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase(); if(CMath.isNumber(arg3.trim())) switch(CMath.s_int(arg3.trim())) { case 0: arg3="NEUTER"; break; case 1: arg3="MALE"; break; case 2: arg3="FEMALE"; break; } Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"SEX","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase(); if(arg2.equals("==")) returnable=arg3.startsWith(sex); else if(arg2.equals("!=")) returnable=!arg3.startsWith(sex); else { scriptableError(scripted,"SEX","Syntax",evaluable); return returnable; } } break; } case 91: // datetime { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) scriptableError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { String val=null; switch(index) { case 2: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 3: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 4: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getMonth(); break; case 5: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getYear(); break; default: val=""+CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay(); break; } returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME"); } break; } case 13: // stat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"STAT","Syntax",evaluable); break; } if(E==null) returnable=false; else { String val=getStatValue(E,arg2); if(val==null) { scriptableError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"STAT"); } break; } case 52: // gstat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"GSTAT","Syntax",evaluable); break; } if(E==null) returnable=false; else { String val=getGStatValue(E,arg2); if(val==null) { scriptableError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT"); } break; } case 19: // position { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase(); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"POSITION","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex="STANDING"; if(CMLib.flags().isSleeping(E)) sex="SLEEPING"; else if(CMLib.flags().isSitting(E)) sex="SITTING"; if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"POSITION","Syntax",evaluable); return returnable; } } break; } case 20: // level { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"LEVEL","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { int val1=E.envStats().level(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL"); } break; } case 80: // questpoints { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"QUESTPOINTS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getQuestPoint(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS"); } break; } case 83: // qvar { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); Quest Q=getQuest(arg1); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"QVAR","Syntax",evaluable); return returnable; } if(Q==null) returnable=false; else returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR"); break; } case 84: // math { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); if(!CMath.isMathExpression(arg1)) { scriptableError(scripted,"MATH","Syntax",evaluable); return returnable; } if(!CMath.isMathExpression(arg3)) { scriptableError(scripted,"MATH","Syntax",evaluable); return returnable; } returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH"); break; } case 81: // trains { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"TRAINS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getTrains(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS"); } break; } case 82: // pracs { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"PRACS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getPractices(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS"); } break; } case 66: // clanrank { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLANRANK","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { int val1=(E instanceof MOB)?((MOB)E).getClanRole():-1; returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK"); } break; } case 64: // deity { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"DEITY","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).getWorshipCharID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"DEITY","Syntax",evaluable); return returnable; } } break; } case 68: // clandata { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLANDATA","Syntax",evaluable); return returnable; } String clanID=null; if((E!=null)&&(E instanceof MOB)) clanID=((MOB)E).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); Clan C=CMLib.clans().findClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(arg2.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} String whichVal=""; switch(whichVar) { case 0: whichVal=C.getAcceptanceSettings(); break; case 1: whichVal=C.getDetail(monster); break; case 2: whichVal=C.getDonation(); break; case 3: whichVal=""+C.getExp(); break; case 4: whichVal=Clan.GVT_DESCS[C.getGovernment()]; break; case 5: whichVal=C.getMorgue(); break; case 6: whichVal=C.getPolitics(); break; case 7: whichVal=C.getPremise(); break; case 8: whichVal=C.getRecall(); break; case 9: whichVal=""+C.getSize(); break; // size case 10: whichVal=Clan.CLANSTATUS_DESC[C.getStatus()]; break; case 11: whichVal=""+C.getTaxes(); break; case 12: whichVal=""+C.getTrophies(); break; case 13: whichVal=""+C.getType(); break; // type case 14: { Vector areas=C.getControlledAreas(); StringBuffer list=new StringBuffer(""); for(int i=0;i<areas.size();i++) list.append("\""+((Environmental)areas.elementAt(i)).name()+"\" "); whichVal=list.toString().trim(); break; // areas } case 15: { DVector members=C.getMemberList(); StringBuffer list=new StringBuffer(""); for(int i=0;i<members.size();i++) list.append("\""+((String)members.elementAt(i,1))+"\" "); whichVal=list.toString().trim(); break; // memberlist } case 16: MOB M=C.getResponsibleMember(); if(M!=null) whichVal=M.Name(); break; // topmember default: scriptableError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); break; } if(CMath.isNumber(whichVal.trim())&&CMath.isNumber(arg4.trim())) returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA"); else returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA"); } break; } case 65: // clan { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"CLAN","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).getClanID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"CLAN","Syntax",evaluable); return returnable; } } break; } case 88: // mood { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { scriptableError(scripted,"MOOD","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else if(E.fetchEffect("Mood")!=null) { String sex=E.fetchEffect("Mood").text(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { scriptableError(scripted,"MOOD","Syntax",evaluable); return returnable; } } break; } case 21: // class { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().displayClassName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } } break; } case 22: // baseclass { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"CLASS","Syntax",evaluable); return returnable; } } break; } case 23: // race { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"RACE","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().raceName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"RACE","Syntax",evaluable); return returnable; } } break; } case 24: //racecat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"RACECAT","Syntax",evaluable); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { scriptableError(scripted,"RACECAT","Syntax",evaluable); return returnable; } } break; } case 25: // goldamt { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return returnable; } returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT"); } break; } case 78: // exp { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"EXP","Syntax",evaluable); break; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { int val1=((MOB)E).getExperience(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP"); } break; } case 76: // value { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),2)); if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0)) { scriptableError(scripted,"VALUE","Syntax",evaluable); break; } if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { scriptableError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase())); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"VALUE","Syntax",evaluable); return returnable; } returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT"); } break; } case 26: // objtype { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1).toUpperCase()); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"OBJTYPE","Syntax",evaluable); return returnable; } if(E==null) returnable=false; else { String sex=CMClass.classID(E).toUpperCase(); if(arg2.equals("==")) returnable=sex.indexOf(arg3)>=0; else if(arg2.equals("!=")) returnable=sex.indexOf(arg3)<0; else { scriptableError(scripted,"OBJTYPE","Syntax",evaluable); return returnable; } } break; } case 27: // var { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1).toUpperCase(); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),2); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),2)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { scriptableError(scripted,"VAR","Syntax",evaluable); return returnable; } String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { scriptableError(scripted,"VAR","Syntax",evaluable); return returnable; } break; } case 41: // eval { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg3=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(evaluable.substring(y+1,z),1)); if(arg3.length()==0) { scriptableError(scripted,"EVAL","Syntax",evaluable); return returnable; } if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { scriptableError(scripted,"EVAL","Syntax",evaluable); return returnable; } break; } case 40: // number { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) if(!Character.isDigit(val.charAt(i))) { isnumber=false; break;} returnable=isnumber; break; } case 42: // randnum { String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s.trim())) arg1=CMath.s_parseIntExpression(arg1s.trim()); else arg1=CMParms.parse(arg1s.trim()).size(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)).trim(); int arg3=0; if(CMath.isMathExpression(arg3s.trim())) arg3=CMath.s_parseIntExpression(arg3s.trim()); else arg3=CMParms.parse(arg3s.trim()).size(); arg3=CMLib.dice().roll(1,arg3,0); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM"); break; } case 71: // rand0num { String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s)) arg1=CMath.s_parseIntExpression(arg1s); else arg1=CMParms.parse(arg1s).size(); String arg2=CMParms.getCleanBit(evaluable.substring(y+1,z),1); String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),1)).trim(); int arg3=0; if(CMath.isMathExpression(arg3s)) arg3=CMath.s_parseIntExpression(arg3s); else arg3=CMParms.parse(arg3s).size(); arg3=CMLib.dice().roll(1,arg3,-1); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM"); break; } case 53: // incontainer { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(arg2.length()==0) returnable=(((MOB)E).riding()==null); else if(E2!=null) returnable=(((MOB)E).riding()==E2); else returnable=false; } else if(E instanceof Item) { if(arg2.length()==0) returnable=(((Item)E).container()==null); else if(E2!=null) returnable=(((Item)E).container()==E2); else returnable=false; } else returnable=false; break; } default: scriptableError(scripted,"Unknown Eval",preFab,evaluable); return returnable; } if((z>=0)&&(z<=evaluable.length())) { evaluable=evaluable.substring(z+1).trim(); uevaluable=uevaluable.substring(z+1).trim(); } switch(joined) { case 1: returnable=lastreturnable&&returnable; break; case 2: returnable=lastreturnable||returnable; break; case 4: returnable=!returnable; break; case 5: returnable=lastreturnable&&(!returnable); break; case 6: returnable=lastreturnable||(!returnable); break; default: break; } joined=0; } } return returnable; } public String functify(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, String msg, Object[] tmp, String evaluable) { String uevaluable=evaluable.toUpperCase().trim(); StringBuffer results = new StringBuffer(""); while(evaluable.length()>0) { int y=evaluable.indexOf("("); int z=evaluable.indexOf(")"); String preFab=(y>=0)?uevaluable.substring(0,y).trim():""; Integer funcCode=(Integer)funcH.get(preFab); if(funcCode==null) funcCode=new Integer(0); if(y==0) { int depth=0; int i=0; while((++i)<evaluable.length()) { char c=evaluable.charAt(i); if((c==')')&&(depth==0)) { String expr=evaluable.substring(1,i); evaluable=evaluable.substring(i+1); uevaluable=uevaluable.substring(i+1); results.append(functify(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,expr)); break; } else if(c=='(') depth++; else if(c==')') depth--; } z=evaluable.indexOf(")"); } else if((y<0)||(z<y)) { scriptableError(scripted,"()","Syntax",evaluable); break; } else { tickStatus=Tickable.STATUS_MISC2+funcCode.intValue(); switch(funcCode.intValue()) { case 1: // rand { results.append(CMLib.dice().rollPercentage()); break; } case 2: // has { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Vector choices=new Vector(); if(E==null) choices=new Vector(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).inventorySize();i++) { Item I=((MOB)E).fetchInventory(i); if((I!=null)&&(I.amWearingAt(Item.IN_INVENTORY))&&(I.container()==null)) choices.addElement(I); } } else if(E instanceof Item) { choices.addElement(E); if(E instanceof Container) choices=((Container)E).getContents(); } else if(E instanceof Room) { for(int i=0;i<((Room)E).numItems();i++) { Item I=((Room)E).fetchItem(i); if((I!=null)&&(I.container()==null)) choices.addElement(I); } } if(choices.size()>0) results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name()); break; } case 74: // hasnum { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((item.length()==0)||(E==null)) scriptableError(scripted,"HASNUM","Syntax",evaluable); else { Item I=null; int num=0; if(E instanceof MOB) { MOB M=(MOB)E; for(int i=0;i<M.inventorySize();i++) { I=M.fetchInventory(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; results.append(""+num); } else if(E instanceof Room) { Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.fetchItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } } break; } case 3: // worn { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Vector choices=new Vector(); if(E==null) choices=new Vector(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).inventorySize();i++) { Item I=((MOB)E).fetchInventory(i); if((I!=null)&&(!I.amWearingAt(Item.IN_INVENTORY))&&(I.container()==null)) choices.addElement(I); } } else if((E instanceof Item)&&(!(((Item)E).amWearingAt(Item.IN_INVENTORY)))) { choices.addElement(E); if(E instanceof Container) choices=((Container)E).getContents(); } if(choices.size()>0) results.append(((Item)choices.elementAt(CMLib.dice().roll(1,choices.size(),-1))).name()); break; } case 4: // isnpc case 5: // ispc results.append("[unimplemented function]"); break; case 87: // isbirthday { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null)) { MOB mob=(MOB)E; TimeClock C=CMClass.globalClock(); int day=C.getDayOfMonth(); int month=C.getMonth(); int year=C.getYear(); int bday=mob.playerStats().getBirthday()[0]; int bmonth=mob.playerStats().getBirthday()[1]; if((month>bmonth)||((month==bmonth)&&(day>bday))) year++; StringBuffer timeDesc=new StringBuffer(""); if(C.getDaysInWeek()>0) { long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth(); x=x+((long)(bmonth-1))*((long)C.getDaysInMonth()); x=x+bmonth; timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", "); } timeDesc.append("the "+bday+CMath.numAppendage(bday)); timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]); if(C.getYearNames().length>0) timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year)); results.append(timeDesc.toString()); } break; } case 6: // isgood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) { Faction.FactionRange FR=CMLib.factions().getRange(CMLib.factions().AlignID(),((MOB)E).fetchFaction(CMLib.factions().AlignID())); if(FR!=null) results.append(FR.name()); else results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID())); } break; } case 8: // isevil { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(CMStrings.capitalizeAndLower(CMLib.flags().getAlignmentName(E)).toLowerCase()); break; } case 9: // isneutral { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(((MOB)E).fetchFaction(CMLib.factions().AlignID())); break; } case 11: // isimmort results.append("[unimplemented function]"); break; case 54: // isalive { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) results.append(((MOB)E).healthText(null)); else results.append(E.name()+" is dead."); break; } case 58: // isable { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) { String s=((MOB)E).fetchExpertise(X.ID()); if(s!=null) results.append(s); } else { Ability A=((MOB)E).findAbility(arg2); if(A!=null) results.append(""+A.proficiency()); } } break; } case 59: // isopen { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); boolean returnable=false; if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } results.append(""+returnable); break; } case 60: // islocked { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); int dir=Directions.getGoodDirectionCode(arg1); if(dir<0) { Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) results.append(((Container)E).keyName()); else if((E!=null)&&(E instanceof Exit)) results.append(((Exit)E).keyName()); } else if(lastKnownLocation!=null) { Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) results.append(E.keyName()); } break; } case 62: // callfunc { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); String found=null; boolean validFunc=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) scriptableError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else results.append(found); break; } case 61: // strin { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Vector V=CMParms.parse(arg1.toUpperCase()); results.append(V.indexOf(arg2.toUpperCase())); break; } case 55: // ispkill { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) results.append("false"); else if(CMath.bset(((MOB)E).getBitmap(),MOB.ATT_PLAYERKILL)) results.append("true"); else results.append("false"); break; } case 10: // isfight { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat())) results.append(((MOB)E).getVictim().name()); break; } case 12: // ischarmed { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { Vector V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING); for(int v=0;v<V.size();v++) results.append((((Ability)V.elementAt(v)).name())+" "); } break; } case 15: // isfollow { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null) &&(((MOB)E).amFollowing().location()==lastKnownLocation)) results.append(((MOB)E).amFollowing().name()); break; } case 73: // isservant { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0)) results.append(((MOB)E).getLiegeID()); break; } case 56: // name case 7: // isname { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.name()); break; } case 75: // currency { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null)results.append(CMLib.beanCounter().getCurrency(E)); break; } case 14: // affected { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { if(((MOB)E).numAllEffects()>0) results.append(E.fetchEffect(CMLib.dice().roll(1,((MOB)E).numAllEffects(),-1)).name()); } else if((E!=null)&&(E.numEffects()>0)) results.append(E.fetchEffect(CMLib.dice().roll(1,E.numEffects(),-1)).name()); break; } case 69: // isbehave { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) for(int i=0;i<E.numBehaviors();i++) results.append(E.fetchBehavior(i).ID()+" "); break; } case 70: // ipaddress { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) results.append(((MOB)E).session().getAddress()); break; } case 28: // questwinner case 29: // questmob case 31: // isquestmobalive results.append("[unimplemented function]"); break; case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); int num=0; Vector MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } results.append(num); break; } case 33: // nummobs { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Vector MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } }catch(NoSuchElementException nse){} results.append(num); break; } case 34: // numracesinarea { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Room R=null; MOB M=null; for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } results.append(num); break; } case 35: // numraces { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Room R=null; MOB M=null; try { for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { R=(Room)e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } }catch(NoSuchElementException nse){} results.append(num); break; } case 30: // questobj results.append("[unimplemented function]"); break; case 16: // hitprcnt { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); int val1=(int)Math.round(hitPctD*100.0); results.append(val1); } break; } case 50: // isseason { if(monster.location()!=null) results.append(TimeClock.SEASON_DESCS[monster.location().getArea().getTimeObj().getSeasonCode()]); break; } case 51: // isweather { if(monster.location()!=null) results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]); break; } case 57: // ismoon { if(monster.location()!=null) results.append(TimeClock.PHASE_DESC[monster.location().getArea().getTimeObj().getMoonPhase()]); break; } case 38: // istime { if(lastKnownLocation!=null) results.append(TimeClock.TOD_DESC[lastKnownLocation.getArea().getTimeObj().getTODCode()].toLowerCase()); break; } case 39: // isday { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth()); break; } case 43: // roommob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); if(which!=null) results.append(which.name()); break; } case 44: // roomitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which=I; break;} ct++; } } if(which!=null) results.append(which.name()); break; } case 45: // nummobsroom { int num=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if((name.length()>0)&&(!name.equalsIgnoreCase("*"))) { num=0; Vector MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } results.append(""+num); break; } case 63: // numpcsroom { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.numPCInhabitants()); break; } case 79: // numpcsarea { if(lastKnownLocation!=null) { int num=0; for(int s=0;s<CMLib.sessions().size();s++) { Session S=CMLib.sessions().elementAt(s); if((S!=null)&&(S.mob()!=null)&&(S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } results.append(""+num); } break; } case 77: // explored { String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),1)); Environmental E=getArgumentItem(whom,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { Area A=null; if(!where.equalsIgnoreCase("world")) { Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 instanceof Area) A=(Area)E2; else A=CMLib.map().getArea(where); } if((lastKnownLocation!=null) &&((A!=null)||(where.equalsIgnoreCase("world")))) { int pct=0; MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); results.append(""+pct); } } break; } case 72: // faction { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBit(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Faction F=CMLib.factions().getFaction(arg2); if(F==null) scriptableError(scripted,"FACTION","Unknown Faction",arg1); else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID()))) { int value=((MOB)E).fetchFaction(F.factionID()); Faction.FactionRange FR=CMLib.factions().getRange(F.factionID(),value); if(FR!=null) results.append(FR.name()); } break; } case 46: // numitemsroom { int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { Item I=lastKnownLocation.fetchItem(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 47: //mobitem { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(evaluable.substring(y+1,z),0)); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); Item which=null; int ct=1; if(M!=null) for(int i=0;i<M.inventorySize();i++) { Item I=M.fetchInventory(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which=I; break;} ct++; } } if(which!=null) results.append(which.name()); break; } case 48: // numitemsmob { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); MOB which=null; if(lastKnownLocation!=null) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); int ct=1; if(which!=null) for(int i=0;i<which.inventorySize();i++) { Item I=which.fetchInventory(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 36: // ishere { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().name()); break; } case 17: // inroom { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(CMLib.map().getExtendedRoomID(lastKnownLocation)); else results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E))); break; } case 90: // inarea { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name()); else { Room R=CMLib.map().roomLocation(E); results.append(R==null?"Nowhere":R.getArea().Name()); } break; } case 89: // isrecall { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E))); break; } case 37: // inlocale { String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))); if(parms.trim().length()==0) { if(lastKnownLocation!=null) results.append(lastKnownLocation.name()); } else { Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { Room R=CMLib.map().roomLocation(E); if(R!=null) results.append(R.name()); } } break; } case 18: // sex { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().genderName()); break; } case 91: // datetime { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) scriptableError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) switch(index) { case 2: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 3: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 4: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth()); break; case 5: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear()); break; default: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getTimeOfDay()); break; } break; } case 13: // stat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String val=getStatValue(E,arg2); if(val==null) { scriptableError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 52: // gstat { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String val=getGStatValue(E,arg2); if(val==null) { scriptableError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 19: // position { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex="STANDING"; if(CMLib.flags().isSleeping(E)) sex="SLEEPING"; else if(CMLib.flags().isSitting(E)) sex="SITTING"; results.append(sex); break; } break; } case 20: // level { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.envStats().level()); break; } case 80: // questpoints { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getQuestPoint()); break; } case 83: // qvar { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); if((arg1.length()!=0)&&(arg2.length()!=0)) { Quest Q=getQuest(arg1); if(Q!=null) results.append(Q.getStat(arg2)); } break; } case 84: // math { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); results.append(""+Math.round(CMath.s_parseMathExpression(arg1))); break; } case 85: // islike { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); results.append(CMLib.masking().maskDesc(arg1)); break; } case 86: // strcontains { results.append("[unimplemented function]"); break; } case 81: // trains { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getTrains()); break; } case 92: // isodd { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } if( isodd ) { results.append( CMath.s_long( val.trim() ) ); } break; } case 82: // pracs { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getPractices()); break; } case 68: // clandata { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((E!=null)&&(E instanceof MOB)) clanID=((MOB)E).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); Clan C=CMLib.clans().findClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(arg2.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} String whichVal=""; switch(whichVar) { case 0: whichVal=C.getAcceptanceSettings(); break; case 1: whichVal=C.getDetail(monster); break; case 2: whichVal=C.getDonation(); break; case 3: whichVal=""+C.getExp(); break; case 4: whichVal=Clan.GVT_DESCS[C.getGovernment()]; break; case 5: whichVal=C.getMorgue(); break; case 6: whichVal=C.getPolitics(); break; case 7: whichVal=C.getPremise(); break; case 8: whichVal=C.getRecall(); break; case 9: whichVal=""+C.getSize(); break; // size case 10: whichVal=Clan.CLANSTATUS_DESC[C.getStatus()]; break; case 11: whichVal=""+C.getTaxes(); break; case 12: whichVal=""+C.getTrophies(); break; case 13: whichVal=""+C.getType(); break; // type case 14: { Vector areas=C.getControlledAreas(); StringBuffer list=new StringBuffer(""); for(int i=0;i<areas.size();i++) list.append("\""+((Environmental)areas.elementAt(i)).name()+"\" "); whichVal=list.toString().trim(); break; // areas } case 15: { DVector members=C.getMemberList(); StringBuffer list=new StringBuffer(""); for(int i=0;i<members.size();i++) list.append("\""+((String)members.elementAt(i,1))+"\" "); whichVal=list.toString().trim(); break; // memberlist } case 16: MOB M=C.getResponsibleMember(); if(M!=null) whichVal=M.Name(); break; // topmember default: scriptableError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); break; } results.append(whichVal); } break; } case 67: // hastitle { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(evaluable.substring(y+1,z),0)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)) { MOB M=(MOB)E; results.append(M.playerStats().getActiveTitle()); } break; } case 66: // clanrank { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).getClanRole()+""); break; } case 21: // class { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().displayClassName()); break; } case 64: // deity { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex=((MOB)E).getWorshipCharID(); results.append(sex); } break; } case 65: // clan { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { String sex=((MOB)E).getClanID(); results.append(sex); } break; } case 88: // mood { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(E.fetchEffect("Mood")!=null)) results.append(CMStrings.capitalizeAndLower(E.fetchEffect("Mood").text())); break; } case 22: // baseclass { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getCurrentClass().baseClass()); break; } case 23: // race { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().raceName()); break; } case 24: //racecat { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getMyRace().racialCategory()); break; } case 25: // goldamt { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return results.toString(); } results.append(val1); } break; } case 78: // exp { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=((MOB)E).getExperience(); results.append(val1); } break; } case 76: // value { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0); if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { scriptableError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); return results.toString(); } Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2)); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { scriptableError(scripted,"GOLDAMT","Syntax",evaluable); return results.toString(); } results.append(val1); } break; } case 26: // objtype { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { String sex=CMClass.classID(E).toLowerCase(); results.append(sex); } break; } case 53: // incontainer { String arg1=CMParms.cleanBit(evaluable.substring(y+1,z)); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(((MOB)E).riding()!=null) results.append(((MOB)E).riding().Name()); } else if(E instanceof Item) { if(((Item)E).riding()!=null) results.append(((Item)E).riding().Name()); else if(((Item)E).container()!=null) results.append(((Item)E).container().Name()); else if(E instanceof Container) { Vector V=((Container)E).getContents(); for(int v=0;v<V.size();v++) results.append("\""+((Item)V.elementAt(v)).Name()+"\" "); } } } break; } case 27: // var { String arg1=CMParms.getCleanBit(evaluable.substring(y+1,z),0); String arg2=CMParms.getPastBitClean(evaluable.substring(y+1,z),0).toUpperCase(); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); results.append(val); break; } case 41: // eval results.append("[unimplemented function]"); break; case 40: // number { String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) if(!Character.isDigit(val.charAt(i))) { isnumber=false; break;} if(isnumber) results.append(CMath.s_long(val.trim())); break; } case 42: // randnum { String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,0)); break; } case 71: // rand0num { String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(evaluable.substring(y+1,z))).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,-1)); break; } default: scriptableError(scripted,"Unknown Val",preFab,evaluable); return results.toString(); } } if((z>=0)&&(z<=evaluable.length())) { evaluable=evaluable.substring(z+1).trim(); uevaluable=uevaluable.substring(z+1).trim(); } } return results.toString(); } protected MOB getFirstPC(MOB monster, MOB randMOB, Room room) { if((randMOB!=null)&&(randMOB!=monster)) return randMOB; MOB M=null; if(room!=null) for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if((!M.isMonster())&&(M!=monster)) { HashSet seen=new HashSet(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } return M; } } return null; } protected MOB getFirstAnyone(MOB monster, MOB randMOB, Room room) { if((randMOB!=null)&&(randMOB!=monster)) return randMOB; MOB M=null; if(room!=null) for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if(M!=monster) { HashSet seen=new HashSet(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } return M; } } return null; } public String execute(Environmental scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, Vector script, String msg, Object[] tmp) { tickStatus=Tickable.STATUS_START; for(int si=1;si<script.size();si++) { String s=((String)script.elementAt(si)).trim(); String cmd=CMParms.getCleanBit(s,0).toUpperCase(); Integer methCode=(Integer)methH.get(cmd); if((methCode==null)&&(cmd.startsWith("MP"))) for(int i=0;i<methods.length;i++) if(methods[i].startsWith(cmd)) methCode=new Integer(i); if(methCode==null) methCode=new Integer(0); tickStatus=Tickable.STATUS_MISC3+methCode.intValue(); if(cmd.length()==0) continue; switch(methCode.intValue()) { case 57: // <SCRIPT> { StringBuffer jscript=new StringBuffer(""); while((++si)<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equalsIgnoreCase("</SCRIPT>")) break; jscript.append(s+"\n"); } if(CMSecurity.isApprovedJScript(jscript)) { Context cx = Context.enter(); try { JScriptEvent scope = new JScriptEvent(scripted,source,target,monster,primaryItem,secondaryItem,msg); cx.initStandardObjects(scope); String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString","setPlayerSetOverride"}; scope.defineFunctionProperties(names, JScriptEvent.class, ScriptableObject.DONTENUM); cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null); } catch(Exception e) { Log.errOut("Scriptable",scripted.name()+"/"+CMLib.map().getExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage()); } Context.exit(); } else if(CMProps.getIntVar(CMProps.SYSTEMI_JSCRIPTS)==1) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,"A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script."); } break; } case 19: // if { String conditionStr=(s.substring(2).trim()); boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,conditionStr); Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundendif=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("ENDIF")&&(depth==0)) { foundendif=true; break; } else if(cmd.equals("ELSE")&&(depth==0)) { condition=!condition; if(s.substring(4).trim().length()>0) { script.setElementAt("ELSE",si); script.insertElementAt(s.substring(4).trim(),si+1); } } else { if(condition) V.addElement(s); if(cmd.equals("IF")) depth++; else if(cmd.equals("ENDIF")) depth--; } si++; } if(!foundendif) { scriptableError(scripted,"IF","Syntax"," Without ENDIF!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { //source.tell("Starting "+conditionStr); //for(int v=0;v<V.size();v++) // source.tell("Statement "+((String)V.elementAt(v))); String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } //source.tell("Stopping "+conditionStr); } break; } case 70: // switch { String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)).trim(); Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundendif=false; boolean ignoreUntilEndScript=false; boolean inCase=false; boolean matchedCase=false; si++; String s2=null; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("ENDSWITCH")&&(depth==0)) { foundendif=true; break; } else if(cmd.equals("CASE")&&(depth==0)) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)).trim(); inCase=var.equalsIgnoreCase(s2); matchedCase=matchedCase||inCase; } else if(cmd.equals("DEFAULT")&&(depth==0)) { inCase=!matchedCase; } else { if(inCase) V.addElement(s); if(cmd.equals("SWITCH")) depth++; else if(cmd.equals("ENDSWITCH")) depth--; } si++; } if(!foundendif) { scriptableError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } } break; } case 62: // for x = 1 to 100 { if(CMParms.numBits(s)<6) { scriptableError(scripted,"FOR","Syntax","5 parms required!"); tickStatus=Tickable.STATUS_END; return null; } String varStr=CMParms.getBit(s,1); if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1)))) { scriptableError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2.."); tickStatus=Tickable.STATUS_END; return null; } int whichVar=CMath.s_int(Character.toString(varStr.charAt(1))); if((tmp[whichVar] instanceof String) &&(((String)tmp[whichVar]).length()>1) &&(((String)tmp[whichVar]).startsWith(" ")) &&(CMath.isInteger(((String)tmp[whichVar]).trim()))) { scriptableError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!"); tickStatus=Tickable.STATUS_END; return null; } if((!CMParms.getBit(s,2).equals("="))&&(!CMParms.getBit(s,4).equalsIgnoreCase("to"))) { scriptableError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3).trim()).trim(); String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,4).trim()).trim(); if((!CMath.isInteger(from))||(!CMath.isInteger(to))) { scriptableError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!"); tickStatus=Tickable.STATUS_END; return null; } Vector V=new Vector(); V.addElement(""); int depth=0; boolean foundnext=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si)).trim(); cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) ignoreUntilEndScript=true; else if(cmd.equals("</SCRIPT>")) ignoreUntilEndScript=false; else if(ignoreUntilEndScript){} else if(cmd.equals("NEXT")&&(depth==0)) { foundnext=true; break; } else { V.addElement(s); if(cmd.equals("FOR")) depth++; else if(cmd.equals("NEXT")) depth--; } si++; } if(!foundnext) { scriptableError(scripted,"FOR","Syntax"," Without NEXT!"); tickStatus=Tickable.STATUS_END; return null; } if(V.size()>1) { //source.tell("Starting "+conditionStr); //for(int v=0;v<V.size();v++) // source.tell("Statement "+((String)V.elementAt(v))); int toInt=CMath.s_int(to); int fromInt=CMath.s_int(from); int increment=(toInt>=fromInt)?1:-1; String response=null; for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment) { tmp[whichVar]=" "+forLoop; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) break; } tmp[whichVar]=" "+toInt; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } tmp[whichVar]=null; //source.tell("Stopping "+conditionStr); } break; } case 50: // break; tickStatus=Tickable.STATUS_END; return null; case 1: // mpasound { String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(8).trim()); //lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo); for(int d=0;d<Directions.NUM_DIRECTIONS;d++) { Room R2=lastKnownLocation.getRoomInDir(d); Exit E2=lastKnownLocation.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(E2.isOpen())) R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo); } break; } case 4: // mpjunk { if(s.substring(6).trim().equalsIgnoreCase("all")) { while(monster.inventorySize()>0) { Item I=monster.fetchInventory(0); if(I!=null) { if(I.owner()==null) I.setOwner(monster); I.destroy(); } else break; } } else { Environmental E=getArgumentItem(s.substring(6).trim(),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Item I=null; if(E instanceof Item) I=(Item)E; if(I==null) I=monster.fetchInventory(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); if((I==null)&&(scripted instanceof Room)) I=((Room)scripted).fetchAnyItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); if(I!=null) I.destroy(); } break; } case 2: // mpecho { if(lastKnownLocation!=null) lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim())); break; } case 13: // mpunaffect { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String which=CMParms.getPastBitClean(s,1); if(newTarget!=null) if(which.equalsIgnoreCase("all")||(which.length()==0)) { for(int a=newTarget.numEffects()-1;a>=0;a--) { Ability A=newTarget.fetchEffect(a); if(A!=null) A.unInvoke(); } } else { Ability A=newTarget.fetchEffect(which); if(A!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPUNAFFECTED by "+A.Name()); A.unInvoke(); if(newTarget.fetchEffect(which)==A) newTarget.delEffect(A); } } break; } case 3: // mpslay { Environmental newTarget=getArgumentItem(CMParms.getPastBitClean(s,0),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) CMLib.combat().postDeath(monster,(MOB)newTarget,null); break; } case 16: // mpset { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getCleanBit(s,2); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(arg2,arg3); found=true; break; } } if((!found)&&(newTarget instanceof MOB)) { MOB M=(MOB)newTarget; for(int i=0;i<CharStats.STAT_DESCS.length;i++) if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } if(!found) for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++) if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1); M.baseEnvStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } if(!found) { scriptableError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverEnvStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { ((MOB)newTarget).baseCharStats().getCurrentClass().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverEnvStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 63: // mpargset { String arg1=CMParms.getCleanBit(s,1); String arg2=CMParms.getPastBitClean(s,1); if((arg1.length()!=2)||(!arg1.startsWith("$"))) { scriptableError(scripted,"MPARGSET","Syntax","Invalid argument var: "+arg1+" for "+scripted.Name()); break; } Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(O==null) O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((O==null) &&((!arg2.trim().startsWith("$")) ||(arg2.length()<2) ||((!Character.isDigit(arg2.charAt(1))) &&(!Character.isLetter(arg2.charAt(1)))))) O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2); char c=arg1.charAt(1); if(Character.isDigit(c)) { if((O instanceof String)&&(((String)O).equalsIgnoreCase("null"))) O=null; tmp[CMath.s_int(Character.toString(c))]=O; } else switch(arg1.charAt(1)) { case 'N': case 'n': if(O instanceof MOB) source=(MOB)O; break; case 'B': case 'b': if(O instanceof Environmental) lastLoaded=(Environmental)O; break; case 'I': case 'i': if(O instanceof Environmental) scripted=(Environmental)O; if(O instanceof MOB) monster=(MOB)O; break; case 'T': case 't': if(O instanceof Environmental) target=(Environmental)O; break; case 'O': case 'o': if(O instanceof Item) primaryItem=(Item)O; break; case 'P': case 'p': if(O instanceof Item) secondaryItem=(Item)O; break; case 'd': case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break; default: scriptableError(scripted,"MPARGSET","Syntax","Invalid argument var: "+arg1+" for "+scripted.Name()); break; } break; } case 35: // mpgset { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=CMParms.getCleanBit(s,2); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(newTarget.getStatCodes()[i],arg3); found=true; break; } } if(!found) if(newTarget instanceof MOB) { for(int i=0;i<CMObjectBuilder.GENMOBCODES.length;i++) { if(CMObjectBuilder.GENMOBCODES[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i]))-1); CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,CMObjectBuilder.GENMOBCODES[i],arg3); found=true; break; } } if(!found) { MOB M=(MOB)newTarget; for(int i=0;i<CharStats.STAT_DESCS.length;i++) { if(CharStats.STAT_DESCS[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0)))) M.baseCharStats().setStat(i,arg3.charAt(0)); else M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } if(!found) for(int i=0;i<M.baseEnvStats().getStatCodes().length;i++) { if(M.baseEnvStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseEnvStats().getStat(M.baseEnvStats().getStatCodes()[i]))-1); M.baseEnvStats().setStat(arg2,arg3); found=true; break; } } if((!found)&&(M.playerStats()!=null)) for(int i=0;i<M.playerStats().getStatCodes().length;i++) if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) for(int i=0;i<M.baseState().getStatCodes().length;i++) if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } } else if(newTarget instanceof Item) { for(int i=0;i<CMObjectBuilder.GENITEMCODES.length;i++) { if(CMObjectBuilder.GENITEMCODES[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i]))-1); CMLib.coffeeMaker().setGenItemStat((Item)newTarget,CMObjectBuilder.GENITEMCODES[i],arg3); found=true; break; } } } if(!found) { scriptableError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverEnvStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { ((MOB)newTarget).baseCharStats().getCurrentClass().fillOutMOB(((MOB)newTarget),((MOB)newTarget).baseEnvStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverEnvStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 11: // mpexp { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { int baseLevel=newTarget.baseEnvStats().level(); int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience(baseLevel-1); int thisLevelExpNeeded=CMLib.leveler().getLevelExperience(baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false); } break; } case 59: // mpquestpoints { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setQuestPoint(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 65: // MPQSET { String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); Environmental obj=getArgumentItem(CMParms.getPastBitClean(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Quest Q=getQuest(qstr); if(Q==null) scriptableError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name()); else if(var.equalsIgnoreCase("QUESTOBJ")) { if(obj==null) scriptableError(scripted,"MPQSET","Syntax","Unknown object "+CMParms.getPastBitClean(s,2)+" for "+scripted.Name()); else { obj.baseEnvStats().setDisposition(obj.baseEnvStats().disposition()|EnvStats.IS_UNSAVABLE); obj.recoverEnvStats(); Q.runtimeRegisterObject(obj); } } else { if(val.equals("++")) val=""+(CMath.s_int(Q.getStat(var))+1); if(val.equals("--")) val=""+(CMath.s_int(Q.getStat(var))-1); Q.setStat(var,val); } break; } case 66: // MPLOG { String type=CMParms.getCleanBit(s,1).toUpperCase(); String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); if(type.startsWith("E")) Log.errOut(head,val); else if(type.startsWith("I")||type.startsWith("S")) Log.infoOut(head,val); else if(type.startsWith("D")) Log.debugOut(head,val); else scriptableError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name()); break; } case 67: // MPCHANNEL { String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); boolean sysmsg=channel.startsWith("!"); if(sysmsg) channel=channel.substring(1); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(CMLib.channels().getChannelCodeNumber(channel)<0) scriptableError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name()); else CMLib.commands().postChannel(monster,channel,val,sysmsg); break; } case 68: // unload { String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); if(!new CMFile(Resources.makeFileResourceName(scriptname),null,false,true).exists()) scriptableError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname)); else { Vector delThese=new Vector(); boolean foundKey=false; scriptname=scriptname.toUpperCase().trim(); String parmname=scriptname; Vector V=Resources.findResourceKeys(parmname); for(Enumeration e=V.elements();e.hasMoreElements();) { String key=(String)e.nextElement(); if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname))) { foundKey=true; delThese.addElement(key);} } if(foundKey) for(int i=0;i<delThese.size();i++) Resources.removeResource((String)delThese.elementAt(i)); } break; } case 60: // trains { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setTrains(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 61: // pracs { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if(newTarget instanceof MOB) { if(CMath.isNumber(val.trim())) ((MOB)newTarget).setPractices(CMath.s_int(val.trim())); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim())); else scriptableError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 5: // mpmload { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Vector Ms=new Vector(); MOB m=CMClass.getMOB(s); if(m!=null) Ms.addElement(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(s,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.elementAt(i) instanceof MOB) { m=(MOB)((MOB)Ms.elementAt(i)).copyOf(); m.text(); m.recoverEnvStats(); m.recoverCharStats(); m.resetToMaxState(); m.bringToLife(lastKnownLocation,true); lastLoaded=m; } } } break; } case 6: // mpoload { // if not mob if(scripted instanceof MOB) { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); int containerIndex=s.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { Vector containers=new Vector(); findSomethingCalledThis(s.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) if((containers.elementAt(c) instanceof Container) &&(((Container)containers.elementAt(c)).capacity()>0)) { container=(Container)containers.elementAt(c); s=s.substring(0,containerIndex).trim(); break; } } long coins=CMLib.english().numPossibleGold(null,s); if(coins>0) { String currency=CMLib.english().numPossibleGoldCurrency(scripted,s); double denom=CMLib.english().numPossibleGoldDenomination(scripted,currency,s); Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); monster.addInventory(C); C.putCoinsBack(); } else if(lastKnownLocation!=null) { Vector Is=new Vector(); Item m=CMClass.getItem(s); if(m!=null) Is.addElement(m); else findSomethingCalledThis(s,(MOB)scripted,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.elementAt(i) instanceof Item) { m=(Item)Is.elementAt(i); if((m!=null)&&(!(m instanceof ArchonOnly))) { m=(Item)m.copyOf(); m.recoverEnvStats(); m.setContainer(container); if(container instanceof MOB) ((MOB)container.owner()).addInventory(m); else if(container instanceof Room) ((Room)container.owner()).addItemRefuse(m,Item.REFUSE_PLAYER_DROP); else monster.addInventory(m); lastLoaded=m; } } } lastKnownLocation.recoverRoomStats(); monster.recoverCharStats(); monster.recoverEnvStats(); monster.recoverMaxState(); } } break; } case 41: // mpoloadroom { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); if(lastKnownLocation!=null) { Vector Is=new Vector(); int containerIndex=s.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { Vector containers=new Vector(); findSomethingCalledThis(s.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) if((containers.elementAt(c) instanceof Container) &&(((Container)containers.elementAt(c)).capacity()>0)) { container=(Container)containers.elementAt(c); s=s.substring(0,containerIndex).trim(); break; } } long coins=CMLib.english().numPossibleGold(null,s); if(coins>0) { String currency=CMLib.english().numPossibleGoldCurrency(monster,s); double denom=CMLib.english().numPossibleGoldDenomination(monster,currency,s); Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); Is.addElement(C); } else { Item I=CMClass.getItem(s); if(I!=null) Is.addElement(I); else findSomethingCalledThis(s,monster,lastKnownLocation,Is,false); } for(int i=0;i<Is.size();i++) { if(Is.elementAt(i) instanceof Item) { Item I=(Item)Is.elementAt(i); if((I!=null)&&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverEnvStats(); lastKnownLocation.addItemRefuse(I,Item.REFUSE_MONSTER_EQ); I.setContainer(container); if(I instanceof Coins) ((Coins)I).putCoinsBack(); if(I instanceof RawMaterial) ((RawMaterial)I).rebundle(); lastLoaded=I; } } } lastKnownLocation.recoverRoomStats(); } break; } case 42: // mphide { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()|EnvStats.IS_NOT_SEEN); newTarget.recoverEnvStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 58: // mpreset { String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)); if(arg.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) CMLib.map().resetArea(lastKnownLocation.getArea()); } else if(arg.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.map().resetRoom(lastKnownLocation); } else { Room R=CMLib.map().getRoom(arg); if(R!=null) CMLib.map().resetRoom(R); else { Area A=CMLib.map().findArea(arg); if(A!=null) CMLib.map().resetArea(A); else scriptableError(scripted,"MPRESET","Syntax","Unknown location: "+arg+" for "+scripted.Name()); } } break; } case 56: // mpstop { Vector V=new Vector(); String who=CMParms.getCleanBit(s,1); if(who.equalsIgnoreCase("all")) { for(int i=0;i<lastKnownLocation.numInhabitants();i++) V.addElement(lastKnownLocation.fetchInhabitant(i)); } else { Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget instanceof MOB) V.addElement(newTarget); } for(int v=0;v<V.size();v++) { Environmental newTarget=(Environmental)V.elementAt(v); if(newTarget instanceof MOB) { MOB mob=(MOB)newTarget; Ability A=null; for(int a=mob.numEffects()-1;a>=0;a--) { A=mob.fetchEffect(a); if((A!=null) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL) &&(A.canBeUninvoked()) &&(!A.isAutoInvoked())) A.unInvoke(); } mob.makePeace(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } } break; } case 43: // mpunhide { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(CMath.bset(newTarget.baseEnvStats().disposition(),EnvStats.IS_NOT_SEEN))) { newTarget.baseEnvStats().setDisposition(newTarget.baseEnvStats().disposition()-EnvStats.IS_NOT_SEEN); newTarget.recoverEnvStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 44: // mpopen { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALid())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),true,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 45: // mpclose { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())&&(((Exit)newTarget).isOpen())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALid())&&(((Container)newTarget).isOpen())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 46: // mplock { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasALock())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasALock())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),true); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 47: // mpunlock { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).isLocked())) { Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).isLocked())) { Container E=(Container)newTarget; E.setLidsNLocks(E.hasALid(),false,E.hasALock(),false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 48: // return tickStatus=Tickable.STATUS_END; return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s.substring(6).trim()); case 7: // mpechoat { String parm=CMParms.getCleanBit(s,1); Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { s=CMParms.getPastBit(s,1).trim(); if(newTarget==monster) lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); else lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s),CMMsg.NO_EFFECT,null); } else if(parm.equalsIgnoreCase("world")) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=CMLib.map().rooms();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } } else if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null)) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } } else if(CMLib.map().getRoom(parm)!=null) CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); else if(CMLib.map().findArea(parm)!=null) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); for(Enumeration e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();) { Room R=(Room)e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1).trim())); } } break; } case 8: // mpechoaround { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { s=CMParms.getPastBit(s,1).trim(); lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); } break; } case 9: // mpcast { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { A.setProficiency(100); A.invoke(monster,newTarget,false,0); } break; } case 30: // mpaffect { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPAFFECTED by "+A.Name()); A.setMiscText(m2); if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY) newTarget.addNonUninvokableEffect(A); else A.invoke(monster,CMParms.parse(m2),newTarget,true,0); } break; } case 31: // mpbehave { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Behavior A=null; if((cast!=null)&&(newTarget!=null)) { A=newTarget.fetchBehavior(cast); if(A==null) A=CMClass.getBehavior(cast); } if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scriptable",newTarget.Name()+" was MPBEHAVED with "+A.name()); A.setParms(m2); if(newTarget.fetchBehavior(A.ID())==null) newTarget.addBehavior(A); } break; } case 32: // mpunbehave { String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,2),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { Behavior A=newTarget.fetchBehavior(cast); if(A!=null) newTarget.delBehavior(A); if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scriptable",newTarget.Name()+" was MPUNBEHAVED with "+A.name()); } break; } case 33: // mptattoo { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); String tattoo=tattooName; if((tattoo.length()>0) &&(Character.isDigit(tattoo.charAt(0))) &&(tattoo.indexOf(" ")>0) &&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim()))) tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim(); if(themob.fetchTattoo(tattoo)!=null) { if(tattooMinus) themob.delTattoo(tattooName); } else if(!tattooMinus) themob.addTattoo(tattooName); } break; } case 55: // mpnotrigger { String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); int triggerCode=-1; for(int i=0;i<progs.length;i++) if(trigger.equalsIgnoreCase(progs[i])) triggerCode=i; if(triggerCode<0) scriptableError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name."); else if(!CMath.isInteger(time.trim())) scriptableError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time."); else { noTrigger.remove(new Integer(triggerCode)); noTrigger.put(new Integer(triggerCode),new Long(System.currentTimeMillis()+CMath.s_long(time.trim()))); } break; } case 54: // mpfaction { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,2)); Faction F=CMLib.factions().getFaction(faction); if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim()))) range=""+(themob.fetchFaction(faction)-CMath.s_int(range.substring(2).trim())); else if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim()))) range=""+(themob.fetchFaction(faction)+CMath.s_int(range.substring(1).trim())); if(CMath.isInteger(range.trim())) themob.addFaction(F.factionID(),CMath.s_int(range.trim())); else { Vector V=CMLib.factions().getRanges(F.factionID()); Faction.FactionRange FR=null; for(int v=0;v<V.size();v++) { Faction.FactionRange FR2=(Faction.FactionRange)V.elementAt(v); if(FR2.name().equalsIgnoreCase(range)) { FR=FR2; break;} } if(FR==null) scriptableError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+"."); else themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2)); } } break; } case 49: // mptitle { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=CMParms.getPastBitClean(s,1); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { MOB themob=(MOB)newTarget; boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); String tattoo=tattooName; if((tattoo.length()>0) &&(Character.isDigit(tattoo.charAt(0))) &&(tattoo.indexOf(" ")>0) &&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")).trim()))) tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim(); if(themob.playerStats()!=null) { if(themob.playerStats().getTitles().contains(tattoo)) { if(tattooMinus) themob.playerStats().getTitles().removeElement(tattooName); } else if(!tattooMinus) themob.playerStats().getTitles().insertElementAt(tattooName,0); } } break; } case 10: // mpkill { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) monster.setVictim((MOB)newTarget); break; } case 51: // mpsetclandata { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((newTarget!=null)&&(newTarget instanceof MOB)) clanID=((MOB)newTarget).getClanID(); else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String clanvar=CMParms.getCleanBit(s,2); String clanval=CMParms.getPastBitClean(s,2); Clan C=CMLib.clans().getClan(clanID); if(C!=null) { int whichVar=-1; for(int i=0;i<clanVars.length;i++) if(clanvar.equalsIgnoreCase(clanVars[i])) { whichVar=i; break;} boolean nosave=false; switch(whichVar) { case 0: C.setAcceptanceSettings(clanval); break; case 1: nosave=true; break; // detail case 2: C.setDonation(clanval); break; case 3: C.setExp(CMath.s_long(clanval.trim())); break; case 4: C.setGovernment(CMath.s_int(clanval.trim())); break; case 5: C.setMorgue(clanval); break; case 6: C.setPolitics(clanval); break; case 7: C.setPremise(clanval); break; case 8: C.setRecall(clanval); break; case 9: nosave=true; break; // size case 10: C.setStatus(CMath.s_int(clanval.trim())); break; case 11: C.setTaxes(CMath.s_double(clanval.trim())); break; case 12: C.setTrophies(CMath.s_int(clanval.trim())); break; case 13: nosave=true; break; // type case 14: nosave=true; break; // areas case 15: nosave=true; break; // memberlist case 16: nosave=true; break; // topmember default: scriptableError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable."); nosave=true; break; } if(!nosave) C.update(); } break; } case 52: // mpplayerclass { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) { Vector V=CMParms.parse(CMParms.getPastBit(s,1)); for(int i=0;i<V.size();i++) { if(CMath.isInteger(((String)V.elementAt(i)).trim())) ((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(((String)V.elementAt(i)).trim())); else { CharClass C=CMClass.findCharClass((String)V.elementAt(i)); if(C!=null) ((MOB)newTarget).baseCharStats().setCurrentClass(C); } } ((MOB)newTarget).recoverCharStats(); } break; } case 12: // mppurge { if(lastKnownLocation!=null) { String s2=CMParms.getPastBitClean(s,0).trim(); Environmental E=null; if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me")) E=scripted; else E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(!((MOB)E).isMonster()) { if(((MOB)E).getStartRoom()!=null) ((MOB)E).getStartRoom().bringMobHere((MOB)E,false); ((MOB)E).session().setKillFlag(true); } else if(((MOB)E).getStartRoom()!=null) ((MOB)E).killMeDead(false); else ((MOB)E).destroy(); } else if(E instanceof Item) { Environmental oE=((Item)E).owner(); ((Item)E).destroy(); if(oE!=null) oE.recoverEnvStats(); } } lastKnownLocation.recoverRoomStats(); } break; } case 14: // mpgoto { s=s.substring(6).trim(); if((s.length()>0)&&(lastKnownLocation!=null)) { Room goHere=null; if(s.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(s,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s),lastKnownLocation); if(goHere!=null) { if(scripted instanceof MOB) goHere.bringMobHere((MOB)scripted,true); else if(scripted instanceof Item) goHere.bringItemHere((Item)scripted,Item.REFUSE_PLAYER_DROP,true); else { goHere.bringMobHere(monster,true); if(!(scripted instanceof MOB)) goHere.delInhabitant(monster); } if(CMLib.map().roomLocation(scripted)==goHere) lastKnownLocation=goHere; } } break; } case 15: // mpat if(lastKnownLocation!=null) { Room lastPlace=lastKnownLocation; String roomName=CMParms.getCleanBit(s,1); if(roomName.length()>0) { s=CMParms.getPastBit(s,1).trim(); Room goHere=null; if(roomName.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(goHere!=null) { goHere.bringMobHere(monster,true); Vector V=new Vector(); V.addElement(""); V.addElement(s.trim()); lastKnownLocation=goHere; execute(scripted,source,target,monster,primaryItem,secondaryItem,V,msg,tmp); lastKnownLocation=lastPlace; lastPlace.bringMobHere(monster,true); if(!(scripted instanceof MOB)) { goHere.delInhabitant(monster); lastPlace.delInhabitant(monster); } } } } break; case 17: // mptransfer { String mobName=CMParms.getCleanBit(s,1); String roomName=""; Room newRoom=null; if(CMParms.numBits(s)>2) { roomName=CMParms.getPastBit(s,1); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); } if((roomName.length()==0)&&(lastKnownLocation!=null)) roomName=lastKnownLocation.roomID(); if(roomName.length()>0) { if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom!=null) { Vector V=new Vector(); if(mobName.startsWith("$")) { Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) V.addElement(E); } if(V.size()==0) { mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName); if(mobName.equalsIgnoreCase("all")) { if(lastKnownLocation!=null) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!V.contains(m))) V.addElement(m); } } } else { MOB findOne=null; Area A=null; if(lastKnownLocation!=null) { findOne=lastKnownLocation.fetchInhabitant(mobName); A=lastKnownLocation.getArea(); if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } if(findOne==null) { findOne=CMLib.map().getPlayer(mobName); if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true))) findOne=null; if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } if((findOne==null)&&(A!=null)) for(Enumeration r=A.getProperMap();r.hasMoreElements();) { Room R=(Room)r.nextElement(); findOne=R.fetchInhabitant(mobName); if((findOne!=null)&&(findOne!=monster)) V.addElement(findOne); } } } for(int v=0;v<V.size();v++) { if(V.elementAt(v) instanceof MOB) { MOB mob=(MOB)V.elementAt(v); HashSet H=mob.getGroupMembers(new HashSet()); for(Iterator e=H.iterator();e.hasNext();) { MOB M=(MOB)e.next(); if((!V.contains(M))&&(M.location()==mob.location())) V.addElement(M); } } } for(int v=0;v<V.size();v++) { if(V.elementAt(v) instanceof MOB) { MOB follower=(MOB)V.elementAt(v); Room thisRoom=follower.location(); // scripting guide calls for NO text -- empty is probably req tho CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMProps.msp("appear.wav",10)); CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE," "); if(thisRoom.okMessage(follower,leaveMsg)&&newRoom.okMessage(follower,enterMsg)) { if(follower.isInCombat()) { CMLib.commands().postFlee(follower,("NOWHERE")); follower.makePeace(); } thisRoom.send(follower,leaveMsg); newRoom.bringMobHere(follower,false); newRoom.send(follower,enterMsg); follower.tell("\n\r\n\r"); CMLib.commands().postLook(follower,true); } } else if((V.elementAt(v) instanceof Item) &&(newRoom!=CMLib.map().roomLocation((Environmental)V.elementAt(v)))) newRoom.bringItemHere((Item)V.elementAt(v),Item.REFUSE_PLAYER_DROP,true); if(V.elementAt(v)==scripted) lastKnownLocation=newRoom; } } } break; } case 25: // mpbeacon { String roomName=CMParms.getCleanBit(s,1); Room newRoom=null; if((roomName.length()>0)&&(lastKnownLocation!=null)) { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1)); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if((newRoom!=null)&&(lastKnownLocation!=null)) { Vector V=new Vector(); if(s.equalsIgnoreCase("all")) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m))) V.addElement(m); } } else { MOB findOne=lastKnownLocation.fetchInhabitant(s); if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster())) V.addElement(findOne); } for(int v=0;v<V.size();v++) { MOB follower=(MOB)V.elementAt(v); if(!follower.isMonster()) follower.setStartRoom(newRoom); } } } break; } case 18: // mpforce { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,1)); if((newTarget!=null)&&(newTarget instanceof MOB)) { Vector V=CMParms.parse(s); ((MOB)newTarget).doCommand(V); } break; } case 20: // mpsetvar { String which=CMParms.getCleanBit(s,1); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,2)); if(!which.equals("*")) { if(E==null) which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which); else if(E instanceof Room) which=CMLib.map().getExtendedRoomID((Room)E); else which=E.Name(); } if((which.length()>0)&&(arg2.length()>0)) mpsetvar(which,arg2,arg3); break; } case 36: // mpsavevar { String which=CMParms.getCleanBit(s,1); String arg2=CMParms.getCleanBit(s,2).toUpperCase(); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if((which.length()>0)&&(arg2.length()>0)) { DVector V=getScriptVarSet(which,arg2); for(int v=0;v<V.size();v++) { which=(String)V.elementAt(0,1); arg2=((String)V.elementAt(0,2)).toUpperCase(); Hashtable H=(Hashtable)Resources.getResource("SCRIPTVAR-"+which); String val=""; if(H!=null) { val=(String)H.get(arg2); if(val==null) val=""; } if(val.length()>0) CMLib.database().DBReCreateData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val); else CMLib.database().DBDeleteData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); } } break; } case 39: // mploadvar { String which=CMParms.getCleanBit(s,1); String arg2=CMParms.getCleanBit(s,2).toUpperCase(); Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()>0) { Vector V=null; which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg2.equals("*")) V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS"); else V=CMLib.database().DBReadData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); if((V!=null)&&(V.size()>0)) for(int v=0;v<V.size();v++) { Vector VAR=(Vector)V.elementAt(v); if(VAR.size()>3) { String varName=(String)VAR.elementAt(2); if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_")) varName=varName.substring((which+"_SCRIPTABLEVARS_").length()); mpsetvar(which,varName,(String)VAR.elementAt(3)); } } } break; } case 40: // MPM2I2M { String arg1=CMParms.getCleanBit(s,1); Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { String arg2=""; String arg3=""; if(CMParms.numBits(s)>2) { arg2=CMParms.getCleanBit(s,2); if(CMParms.numBits(s)>3) arg3=CMParms.getPastBit(s,2); } CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged"); if(caged!=null) { ((Item)caged).baseEnvStats().setAbility(1); ((Item)caged).recoverEnvStats(); } if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null)) { if(arg2.length()>0) ((Item)caged).setName(arg2); if(arg3.length()>0) ((Item)caged).setDisplayText(arg3); lastKnownLocation.addItemRefuse((Item)caged,Item.REFUSE_PLAYER_DROP); ((MOB)E).killMeDead(false); } } else if(E instanceof CagedAnimal) { MOB M=((CagedAnimal)E).unCageMe(); if((M!=null)&&(lastKnownLocation!=null)) { M.bringToLife(lastKnownLocation,true); ((Item)E).destroy(); } } else scriptableError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item."); break; } case 28: // mpdamage { Environmental newTarget=getArgumentItem(CMParms.getCleanBit(s,1),source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3)); String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,3)); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { MOB E=(MOB)newTarget; int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); if((dmg>=E.curState().getHitPoints())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.curState().getHitPoints()-1; if(dmg>0) CMLib.combat().postDamage(E,E,null,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,null); } } else if(newTarget instanceof Item) { Item E=(Item)newTarget; int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); boolean destroy=false; if(E.subjectToWearAndTear()) { if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.usesRemaining()-1; if(dmg>0) E.setUsesRemaining(E.usesRemaining()-dmg); if(E.usesRemaining()<=0) destroy=true; } else if(arg4.equalsIgnoreCase("kill")) destroy=true; if(destroy) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,E.name()+" is destroyed!"); E.destroy(); } } } } break; } case 29: // mptrackto { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,0)); Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1),null,true,0); altStatusTickable=null; } break; } case 53: // mpwalkto { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0)); Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0); altStatusTickable=null; } break; } case 21: //MPENDQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.stopQuest(); else scriptableError(scripted,"MPENDQUEST","Unknown","Quest: "+s); break; } case 69: // MPSTEPQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.stepQuest(); else scriptableError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s); break; } case 23: //MPSTARTQUEST { s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,0).trim()); Quest Q=getQuest(s); if(Q!=null) Q.startQuest(); else scriptableError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s); break; } case 64: //MPLOADQUESTOBJ { String questName=CMParms.getCleanBit(s,1).trim(); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); Quest Q=getQuest(questName); if(Q==null) { scriptableError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName); break; } Object O=Q.getQuestObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2))); if(O==null) { scriptableError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+CMParms.getCleanBit(s,2)+" for Quest: "+questName); break; } String varArg=CMParms.getPastBit(s,2); if((varArg.length()!=2)||(!varArg.startsWith("$"))) { scriptableError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } char c=varArg.charAt(1); if(Character.isDigit(c)) tmp[CMath.s_int(Character.toString(c))]=O; else switch(c) { case 'N': case 'n': if(O instanceof MOB) source=(MOB)O; break; case 'I': case 'i': if(O instanceof Environmental) scripted=(Environmental)O; if(O instanceof MOB) monster=(MOB)O; break; case 'B': case 'b': if(O instanceof Environmental) lastLoaded=(Environmental)O; break; case 'T': case 't': if(O instanceof Environmental) target=(Environmental)O; break; case 'O': case 'o': if(O instanceof Item) primaryItem=(Item)O; break; case 'P': case 'p': if(O instanceof Item) secondaryItem=(Item)O; break; case 'd': case 'D': if(O instanceof Room) lastKnownLocation=(Room)O; break; default: scriptableError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } break; } case 22: //MPQUESTWIN { String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(whoName); if(M==null) M=CMLib.map().getPlayer(whoName); if(M!=null) whoName=M.Name(); if(whoName.length()>0) { s=CMParms.getPastBitClean(s,1); Quest Q=getQuest(s); if(Q!=null) Q.declareWinner(whoName); else scriptableError(scripted,"MYQUESTWIN","Unknown","Quest: "+s); } break; } case 24: // MPCALLFUNC { String named=CMParms.getCleanBit(s,1); String parms=CMParms.getPastBit(s,1).trim(); boolean found=false; Vector scripts=getScripts(); for(int v=0;v<scripts.size();v++) { Vector script2=(Vector)scripts.elementAt(v); if(script2.size()<1) continue; String trigger=((String)script2.elementAt(0)).toUpperCase().trim(); if(getTriggerCode(trigger)==17) { String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(named)) { found=true; execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) scriptableError(scripted,"MPCALLFUNC","Unknown","Function: "+named); break; } case 27: // MPWHILE { String conditionStr=(s.substring(2).trim()); int x=conditionStr.indexOf("("); if(x<0) { scriptableError(scripted,"MPWHILE","Unknown","Condition: "+s); break; } conditionStr=conditionStr.substring(x+1); x=-1; int depth=0; for(int i=0;i<conditionStr.length();i++) if(conditionStr.charAt(i)=='(') depth++; else if((conditionStr.charAt(i)==')')&&((--depth)<0)) { x=i; break; } if(x<0) { scriptableError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } String cmd2=conditionStr.substring(x+1).trim(); conditionStr=conditionStr.substring(0,x); Vector vscript=new Vector(); vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random()); vscript.addElement(cmd2); long time=System.currentTimeMillis(); while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,conditionStr))&&((System.currentTimeMillis()-time)<4000)) execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp); if((System.currentTimeMillis()-time)>=4000) { scriptableError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+conditionStr); break; } break; } case 26: // MPALARM { String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,1)); String parms=CMParms.getPastBit(s,1).trim(); if(CMath.s_int(time.trim())<=0) { scriptableError(scripted,"MPALARM","Syntax","Bad time "+time); break; } if(parms.length()==0) { scriptableError(scripted,"MPALARM","Syntax","No command!"); break; } Vector vscript=new Vector(); vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random()); vscript.addElement(parms); que.insertElementAt(new ScriptableResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg),0); break; } case 37: // mpenable { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,2)); String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(s,3)); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBit(s,3)); Ability A=null; if(cast!=null) { if(newTarget instanceof MOB) A=((MOB)newTarget).fetchAbility(cast); if(A==null) A=CMClass.getAbility(cast); if(A==null) { ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if(D==null) scriptableError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast); else if((newTarget!=null)&&(newTarget instanceof MOB)) ((MOB)newTarget).addExpertise(D.ID); } } if((newTarget!=null) &&(A!=null) &&(newTarget instanceof MOB)) { if(!((MOB)newTarget).isMonster()) Log.sysOut("Scriptable",newTarget.Name()+" was MPENABLED with "+A.Name()); if(p2.trim().startsWith("++")) p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency()); else if(p2.trim().startsWith("--")) p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2))); A.setProficiency(CMath.s_int(p2.trim())); A.setMiscText(m2); if(((MOB)newTarget).fetchAbility(A.ID())==null) ((MOB)newTarget).addAbility(A); } break; } case 38: // mpdisable { Environmental newTarget=getArgumentMOB(CMParms.getCleanBit(s,1),source,monster,target,primaryItem,secondaryItem,msg,tmp); String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(s,1)); if((newTarget!=null)&&(newTarget instanceof MOB)) { Ability A=((MOB)newTarget).findAbility(cast); if(A!=null)((MOB)newTarget).delAbility(A); if((!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scriptable",newTarget.Name()+" was MPDISABLED with "+A.Name()); ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if((newTarget instanceof MOB)&&(D!=null)) ((MOB)newTarget).delExpertise(D.ID); } break; } default: if(cmd.length()>0) { Vector V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); if(V.size()>0) monster.doCommand(V); } break; } } tickStatus=Tickable.STATUS_END; return null; } protected static final Vector empty=new Vector(); protected Vector getScripts() { if(CMSecurity.isDisabled("SCRIPTABLE")) return empty; Vector scripts=null; if(getParms().length()>100) scripts=(Vector)Resources.getResource("PARSEDPRG: "+getParms().substring(0,100)+getParms().length()+getParms().hashCode()); else scripts=(Vector)Resources.getResource("PARSEDPRG: "+getParms()); if(scripts==null) { String script=getParms(); script=CMStrings.replaceAll(script,"`","'"); scripts=parseScripts(script); if(getParms().length()>100) Resources.submitResource("PARSEDPRG: "+getParms().substring(0,100)+getParms().length()+getParms().hashCode(),scripts); else Resources.submitResource("PARSEDPRG: "+getParms(),scripts); } return scripts; } public boolean match(String str, String patt) { if(patt.trim().equalsIgnoreCase("ALL")) return true; if(patt.length()==0) return true; if(str.length()==0) return false; if(str.equalsIgnoreCase(patt)) return true; return false; } private Item makeCheapItem(Environmental E) { Item product=null; if(E instanceof Item) product=(Item)E; else { product=CMClass.getItem("StdItem"); product.setName(E.Name()); product.setDisplayText(E.displayText()); product.setDescription(E.description()); product.setBaseEnvStats((EnvStats)E.baseEnvStats().copyOf()); product.recoverEnvStats(); } return product; } public boolean okMessage(Environmental affecting, CMMsg msg) { if(!super.okMessage(affecting,msg)) return false; if((affecting==null)||(msg.source()==null)) return true; Vector scripts=getScripts(); Vector script=null; boolean tryIt=false; String trigger=null; int triggerCode=0; String str=null; for(int v=0;v<scripts.size();v++) { tryIt=false; script=(Vector)scripts.elementAt(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0)).toUpperCase().trim(); triggerCode=getTriggerCode(trigger); switch(triggerCode) { case 42: // cnclmsg_prog if(canTrigger(42)) { trigger=trigger.substring(12).trim(); String command=CMParms.getCleanBit(trigger,0).toUpperCase().trim(); if(msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command)) { trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); str=""; if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" "; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) tryIt=true; } else if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) tryIt=true; else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=(t.trim()+" "+str.trim()).trim(); tryIt=true; break; } } } } } break; } if(tryIt) { MOB monster=getScriptableMOB(affecting); if(lastKnownLocation==null) lastKnownLocation=msg.source().location(); if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return true; Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; String resp=null; if(msg.target() instanceof MOB) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[10]); else if(msg.target() instanceof Item) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,new Object[10]); else resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[10]); if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL"))) return false; } } return true; } public void executeMsg(Environmental affecting, CMMsg msg) { super.executeMsg(affecting,msg); if((affecting==null)||(msg.source()==null)) return; MOB monster=getScriptableMOB(affecting); if(lastKnownLocation==null) lastKnownLocation=msg.source().location(); if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return; Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; MOB eventMob=monster; if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB)) eventMob=(MOB)defaultItem.owner(); Vector scripts=getScripts(); if(msg.amITarget(eventMob) &&(!msg.amISource(monster)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.source()!=monster)) lastToHurtMe=msg.source(); Vector script=null; for(int v=0;v<scripts.size();v++) { script=(Vector)scripts.elementAt(v); if(script.size()<1) continue; String trigger=((String)script.elementAt(0)).toUpperCase().trim(); int triggerCode=getTriggerCode(trigger); int targetMinorTrigger=-1; switch(triggerCode) { case 1: // greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&canTrigger(1) &&((!(affecting instanceof MOB))||CMLib.flags().canSenseMoving(msg.source(),(MOB)affecting))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 2: // all_greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canActAtAll(monster))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 3: // speech_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3) &&(!msg.amISource(monster)) &&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE))) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { String str=null; if(msg.othersMessage()!=null) str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()),"`","'"); else str=CMStrings.replaceAll(CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()),"`","'"); str=(" "+str+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); trigger=trigger.substring(11).trim(); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str)); return; } else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i); int x=str.indexOf(" "+t+" "); if(x>=0) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim())); return; } } } } break; case 4: // give_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(4) &&((msg.amITarget(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.tool() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if((trigger.equalsIgnoreCase(msg.tool().Name())) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } } } break; case 40: // llook_prog if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40) &&((msg.amITarget(affecting))||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(10).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 41: // execmsg_prog if(canTrigger(41)) { trigger=trigger.substring(12).trim(); String command=CMParms.getCleanBit(trigger,0).toUpperCase().trim(); if(msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command)) { trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); String str=""; if((msg.source().session()!=null)&&(msg.source().session().previousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().previousCMD(),0).toUpperCase()+" "; boolean doIt=false; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) doIt=true; } else if(trigger.trim().equalsIgnoreCase("ALL")||(trigger.trim().length()==0)) doIt=true; else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=(t.trim()+" "+str.trim()).trim(); doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); return; } } } break; case 39: // look_prog if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39) &&((msg.amITarget(affecting))||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 20: // get_prog if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 22: // drop_prog if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 24: // remove_prog if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(11).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 34: // open_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_OPEN; case 35: // close_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_CLOSE; case 36: // lock_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_LOCK; case 37: // unlock_prog { if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_UNLOCK; if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { switch(triggerCode) { case 34: case 36: trigger=trigger.substring(9).trim(); break; case 35: trigger=trigger.substring(10).trim(); break; case 37: trigger=trigger.substring(11).trim(); break; } Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem; if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,null)); return; } } } } break; } case 25: // consume_prog if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(25) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(12).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 21: // put_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); return; } } } } break; case 27: // buy_prog if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27) &&((!(affecting instanceof ShopKeeper)) ||msg.amITarget(affecting)) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } } } break; case 28: // sell_prog if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28) &&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper))) &&(!msg.amISource(monster)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(8).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.tool().Name().toUpperCase())>=0) ||(msg.tool().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.tool().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.tool().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); else que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); return; } } } } break; case 23: // wear_prog if(((msg.targetMinor()==CMMsg.TYP_WEAR) ||(msg.targetMinor()==CMMsg.TYP_HOLD) ||(msg.targetMinor()==CMMsg.TYP_WIELD)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(23) &&(msg.target() instanceof Item) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(9).trim(); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(((" "+trigger+" ").indexOf(msg.target().Name().toUpperCase())>=0) ||(msg.target().ID().equalsIgnoreCase(trigger)) ||(trigger.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).toUpperCase(); if(((" "+msg.target().Name().toUpperCase()+" ").indexOf(" "+t+" ")>=0) ||(msg.target().ID().equalsIgnoreCase(t)) ||(t.equalsIgnoreCase("ALL"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); return; } } } } break; case 19: // bribe_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.amITarget(eventMob)||(!(affecting instanceof MOB))) &&(!msg.amISource(monster))&&canTrigger(19) &&(msg.tool() instanceof Coins) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { trigger=trigger.substring(10).trim(); if(trigger.toUpperCase().startsWith("ANY")||trigger.toUpperCase().startsWith("ALL")) trigger=trigger.substring(3).trim(); else if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster))) break; double t=0.0; if(CMath.isDouble(trigger.trim())) t=CMath.s_double(trigger.trim()); else t=new Integer(CMath.s_int(trigger.trim())).doubleValue(); if((((Coins)msg.tool()).getTotalValue()>=t) ||(trigger.equalsIgnoreCase("ALL")) ||(trigger.equalsIgnoreCase("ANY"))) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null)); return; } } break; case 8: // entry_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8) &&(msg.amISource(eventMob) ||(msg.target()==affecting) ||(msg.tool()==affecting) ||(affecting instanceof Item)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 9: // exit prog if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB)))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 10: // death prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10) &&(msg.amISource(eventMob)||(!(affecting instanceof MOB)))) { MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[10]); return; } break; case 44: // kill prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44) &&((msg.tool()==affecting)||(!(affecting instanceof MOB)))) { MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[10]); return; } break; case 26: // damage prog if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26) &&(msg.amITarget(eventMob)||(msg.tool()==affecting))) { Item I=null; if(msg.tool() instanceof Item) I=(Item)msg.tool(); execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),new Object[10]); return; } break; case 29: // login_prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_LOGIN))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN); registeredSpecialEvents.add(new Integer(CMMsg.TYP_LOGIN)); } if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 32: // level_prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_LEVEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL); registeredSpecialEvents.add(new Integer(CMMsg.TYP_LEVEL)); } if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 30: // logoff_prog if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30) &&(canFreelyBehaveNormal(monster)||(!(affecting instanceof MOB))) &&(!CMLib.flags().isCloaked(msg.source()))) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null)); return; } } break; case 12: // mask_prog if(!canTrigger(12)) break; case 18: // act_prog if((msg.amISource(monster)) ||((triggerCode==18)&&(!canTrigger(18)))) break; case 43: // imask_prog if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43))) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); str=CMStrings.removeColors(str); str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" "; trigger=CMParms.getPastBit(trigger.trim(),0).trim().toUpperCase(); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) doIt=true; else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim(); if(match(str.trim(),trigger)) doIt=true; } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=t; doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; case 38: // social prog if(!msg.amISource(monster) &&canTrigger(38) &&(msg.tool() instanceof Social)) { trigger=CMParms.getPastBit(trigger.trim(),0); if(((Social)msg.tool()).Name().toUpperCase().startsWith(trigger.toUpperCase())) { Item Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name())); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,msg.tool().Name())); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,msg.tool().Name())); return; } } break; case 33: // channel prog if(!registeredSpecialEvents.contains(new Integer(CMMsg.TYP_CHANNEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL); registeredSpecialEvents.add(new Integer(CMMsg.TYP_CHANNEL)); } if(!msg.amISource(monster) &&(CMath.bset(msg.othersMajor(),CMMsg.MASK_CHANNEL)) &&canTrigger(33)) { boolean doIt=false; String channel=CMParms.getBit(trigger.trim(),1); int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL; String str=null; if(channel.equalsIgnoreCase(CMLib.channels().getChannelName(channelInt))) { str=msg.sourceMessage(); if(str==null) str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim(); int dex=str.indexOf("["+channel+"]"); if(dex>0) str=str.substring(dex+2+channel.length()).trim(); else { dex=str.indexOf("'"); int edex=str.lastIndexOf("'"); if(edex>dex) str=str.substring(dex+1,edex); } str=" "+CMStrings.removeColors(str)+" "; str=CMStrings.replaceAll(str,"\n\r"," "); trigger=CMParms.getPastBit(trigger.trim(),1); if((trigger.length()==0)||(trigger.equalsIgnoreCase("all"))) doIt=true; else if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) { trigger=trigger.substring(1).trim().toUpperCase(); if(match(str.trim(),trigger)) doIt=true; } else { int num=CMParms.numBits(trigger); for(int i=0;i<num;i++) { String t=CMParms.getCleanBit(trigger,i).trim(); if(str.indexOf(" "+t+" ")>=0) { str=t; doIt=true; break; } } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; case 31: // regmask prog if(!msg.amISource(monster)&&canTrigger(31)) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); trigger=CMParms.getPastBit(trigger.trim(),0); if(CMParms.getCleanBit(trigger,0).equalsIgnoreCase("p")) doIt=str.trim().equals(trigger.substring(1).trim()); else { Pattern P=(Pattern)patterns.get(trigger); if(P==null) { P=Pattern.compile(trigger, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); patterns.put(trigger,P); } Matcher M=P.matcher(str); doIt=M.find(); if(doIt) str=str.substring(M.start()).trim(); } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) que.addElement(new ScriptableResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str)); else if(msg.target() instanceof Item) que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,(Item)msg.target(),script,1,str)); else que.addElement(new ScriptableResponse(affecting,msg.source(),null,monster,Tool,defaultItem,script,1,str)); return; } } break; } } } protected int getTriggerCode(String trigger) { int x=trigger.indexOf(" "); Integer I=null; if(x<0) I=(Integer)progH.get(trigger.toUpperCase().trim()); else I=(Integer)progH.get(trigger.substring(0,x).toUpperCase().trim()); if(I==null) return 0; return I.intValue(); } public MOB backupMOB=null; public MOB getScriptableMOB(Tickable ticking) { MOB mob=null; if(ticking instanceof MOB) { mob=(MOB)ticking; if(!mob.amDead()) lastKnownLocation=mob.location(); } else if(ticking instanceof Environmental) { Room R=CMLib.map().roomLocation((Environmental)ticking); if(R!=null) lastKnownLocation=R; if((backupMOB==null)||(backupMOB.amDestroyed())||(backupMOB.amDead())) { backupMOB=CMClass.getMOB("StdMOB"); if(backupMOB!=null) { backupMOB.setName(ticking.name()); backupMOB.setDisplayText(ticking.name()+" is here."); backupMOB.setDescription(""); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } else { mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } return mob; } public boolean canTrigger(int triggerCode) { Long L=(Long)noTrigger.get(new Integer(triggerCode)); if(L==null) return true; if(System.currentTimeMillis()<L.longValue()) return false; noTrigger.remove(new Integer(triggerCode)); return true; } public boolean tick(Tickable ticking, int tickID) { super.tick(ticking,tickID); if(!CMProps.getBoolVar(CMProps.SYSTEMB_MUDSTARTED)) return false; MOB mob=getScriptableMOB(ticking); Item defaultItem=(ticking instanceof Item)?(Item)ticking:null; if((mob==null)||(lastKnownLocation==null)) { altStatusTickable=null; return true; } Environmental affecting=(ticking instanceof Environmental)?((Environmental)ticking):null; Vector scripts=getScripts(); int triggerCode=-1; for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++) { Vector script=(Vector)scripts.elementAt(thisScriptIndex); String trigger=""; if(script.size()>0) trigger=((String)script.elementAt(0)).toUpperCase().trim(); triggerCode=getTriggerCode(trigger); tickStatus=Tickable.STATUS_BEHAVIOR+triggerCode; switch(triggerCode) { case 5: // rand_Prog if((!mob.amDead())&&canTrigger(5)) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); } break; case 16: // delay_prog if((!mob.amDead())&&canTrigger(16)) { int targetTick=-1; if(delayTargetTimes.containsKey(new Integer(thisScriptIndex))) targetTick=((Integer)delayTargetTimes.get(new Integer(thisScriptIndex))).intValue(); else { int low=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); int high=CMath.s_int(CMParms.getCleanBit(trigger,2).trim()); if(high<low) high=low; targetTick=CMLib.dice().roll(1,high-low+1,low-1); delayTargetTimes.put(new Integer(thisScriptIndex),new Integer(targetTick)); } int delayProgCounter=0; if(delayProgCounters.containsKey(new Integer(thisScriptIndex))) delayProgCounter=((Integer)delayProgCounters.get(new Integer(thisScriptIndex))).intValue(); else delayProgCounters.put(new Integer(thisScriptIndex),new Integer(0)); if(delayProgCounter==targetTick) { execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); delayProgCounter=-1; } delayProgCounters.remove(new Integer(thisScriptIndex)); delayProgCounters.put(new Integer(thisScriptIndex),new Integer(delayProgCounter+1)); } break; case 7: // fightProg if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7)) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[10]); } else if((ticking instanceof Item) &&canTrigger(7) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); if(CMLib.dice().rollPercentage()<prcnt) { MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[10]); } } break; case 11: // hitprcnt if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11)) { int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),mob.maxState().getHitPoints())); if(mob.curState().getHitPoints()<=floor) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[10]); } else if((ticking instanceof Item) &&canTrigger(11) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) { int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),M.maxState().getHitPoints())); if(M.curState().getHitPoints()<=floor) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[10]); } } break; case 6: // once_prog if(!oncesDone.contains(script)&&canTrigger(6)) { oncesDone.addElement(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); } break; case 14: // time_prog if((mob.location()!=null) &&canTrigger(14) &&(!mob.amDead())) { int lastTimeProgDone=-1; if(lastTimeProgsDone.containsKey(new Integer(thisScriptIndex))) lastTimeProgDone=((Integer)lastTimeProgsDone.get(new Integer(thisScriptIndex))).intValue(); int time=mob.location().getArea().getTimeObj().getTimeOfDay(); if(lastTimeProgDone!=time) { boolean done=false; for(int i=1;i<CMParms.numBits(trigger);i++) { if(time==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); lastTimeProgsDone.remove(new Integer(thisScriptIndex)); lastTimeProgsDone.put(new Integer(thisScriptIndex),new Integer(time)); break; } } if(!done) lastTimeProgsDone.remove(new Integer(thisScriptIndex)); } } break; case 15: // day_prog if((mob.location()!=null)&&canTrigger(15) &&(!mob.amDead())) { int lastDayProgDone=-1; if(lastDayProgsDone.containsKey(new Integer(thisScriptIndex))) lastDayProgDone=((Integer)lastDayProgsDone.get(new Integer(thisScriptIndex))).intValue(); int day=mob.location().getArea().getTimeObj().getDayOfMonth(); if(lastDayProgDone!=day) { boolean done=false; for(int i=1;i<CMParms.numBits(trigger);i++) { if(day==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); lastDayProgsDone.remove(new Integer(thisScriptIndex)); lastDayProgsDone.put(new Integer(thisScriptIndex),new Integer(day)); break; } } if(!done) lastDayProgsDone.remove(new Integer(thisScriptIndex)); } } break; case 13: // quest time prog if(!oncesDone.contains(script)&&canTrigger(13)) { Quest Q=getQuest(CMParms.getCleanBit(trigger,1)); if((Q!=null)&&(Q.running())&&(!Q.stopping())) { int time=CMath.s_int(CMParms.getCleanBit(trigger,2).trim()); if(time>=Q.minsRemaining()) { oncesDone.addElement(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); } } } break; default: break; } } tickStatus=Tickable.STATUS_BEHAVIOR+100; dequeResponses(); altStatusTickable=null; return true; } public void dequeResponses() { try{ tickStatus=Tickable.STATUS_BEHAVIOR+100; for(int q=que.size()-1;q>=0;q--) { ScriptableResponse SB=null; try{SB=(ScriptableResponse)que.elementAt(q);}catch(ArrayIndexOutOfBoundsException x){continue;} if(SB.checkTimeToExecute()) { execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,new Object[10]); que.removeElement(SB); } } }catch(Exception e){Log.errOut("Scriptable",e);} } }
Repaired random mob selection git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@6903 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Behaviors/Scriptable.java
Repaired random mob selection
<ide><path>om/planet_ink/coffee_mud/Behaviors/Scriptable.java <ide> &&(CMath.s_int(CMParms.getCleanBit(trigger,2).trim())<0)) <ide> { <ide> oncesDone.addElement(script); <del> execute(hostObj,mob,mob,mob,null,null,script,null,new Object[10]); <add> execute(hostObj,mob,mob,mob,null,null,script,null,new Object[12]); <ide> return true; <ide> } <ide> } <ide> return monster.amFollowing(); <ide> return null; <ide> case 'r': <del> case 'R': return getFirstPC(monster,null,lastKnownLocation); <add> case 'R': return getRandPC(monster,tmp,lastKnownLocation); <ide> case 'c': <del> case 'C': return getFirstAnyone(monster,null,lastKnownLocation); <add> case 'C': return getRandAnyone(monster,tmp,lastKnownLocation); <ide> case 'w': return primaryItem!=null?primaryItem.owner():null; <ide> case 'W': return secondaryItem!=null?secondaryItem.owner():null; <ide> case 'x': <ide> case 'B': middle=lastLoaded!=null?lastLoaded.displayText():""; break; <ide> case 'c': <ide> case 'C': <del> randMOB=getFirstAnyone(monster,randMOB,lastKnownLocation); <add> randMOB=getRandAnyone(monster,tmp,lastKnownLocation); <ide> if(randMOB!=null) <ide> middle=randMOB.name(); <ide> break; <ide> break; <ide> case 'r': <ide> case 'R': <del> randMOB=getFirstPC(monster,randMOB,lastKnownLocation); <add> randMOB=getRandPC(monster,tmp,lastKnownLocation); <ide> if(randMOB!=null) <ide> middle=randMOB.name(); <ide> break; <ide> middle=((MOB)target).charStats().heshe(); <ide> break; <ide> case 'J': <del> randMOB=getFirstPC(monster,randMOB,lastKnownLocation); <add> randMOB=getRandPC(monster,tmp,lastKnownLocation); <ide> if(randMOB!=null) <ide> middle=randMOB.charStats().heshe(); <ide> break; <ide> middle=((MOB)target).charStats().hisher(); <ide> break; <ide> case 'K': <del> randMOB=getFirstPC(monster,randMOB,lastKnownLocation); <add> randMOB=getRandPC(monster,tmp,lastKnownLocation); <ide> if(randMOB!=null) <ide> middle=randMOB.charStats().hisher(); <ide> break; <ide> return results.toString(); <ide> } <ide> <del> protected MOB getFirstPC(MOB monster, MOB randMOB, Room room) <add> protected MOB getRandPC(MOB monster, Object[] tmp, Room room) <ide> { <del> if((randMOB!=null)&&(randMOB!=monster)) <del> return randMOB; <del> MOB M=null; <del> if(room!=null) <del> for(int p=0;p<room.numInhabitants();p++) <del> { <del> M=room.fetchInhabitant(p); <del> if((!M.isMonster())&&(M!=monster)) <del> { <del> HashSet seen=new HashSet(); <del> while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) <del> { <del> seen.add(M); <del> M=M.amFollowing(); <del> } <del> return M; <del> } <del> } <del> return null; <add> if((tmp[10]==null)||(tmp[10]==monster)) { <add> MOB M=null; <add> if(room!=null) { <add> Vector choices = new Vector(); <add> for(int p=0;p<room.numInhabitants();p++) <add> { <add> M=room.fetchInhabitant(p); <add> if((!M.isMonster())&&(M!=monster)) <add> { <add> HashSet seen=new HashSet(); <add> while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) <add> { <add> seen.add(M); <add> M=M.amFollowing(); <add> } <add> choices.addElement(M); <add> } <add> } <add> if(choices.size() > 0) <add> tmp[10] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); <add> } <add> } <add> return (MOB)tmp[10]; <ide> } <del> protected MOB getFirstAnyone(MOB monster, MOB randMOB, Room room) <add> protected MOB getRandAnyone(MOB monster, Object[] tmp, Room room) <ide> { <del> if((randMOB!=null)&&(randMOB!=monster)) <del> return randMOB; <del> MOB M=null; <del> if(room!=null) <del> for(int p=0;p<room.numInhabitants();p++) <del> { <del> M=room.fetchInhabitant(p); <del> if(M!=monster) <del> { <del> HashSet seen=new HashSet(); <del> while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) <del> { <del> seen.add(M); <del> M=M.amFollowing(); <del> } <del> return M; <del> } <del> } <del> return null; <add> if((tmp[11]==null)||(tmp[11]==monster)) { <add> MOB M=null; <add> if(room!=null) { <add> Vector choices = new Vector(); <add> for(int p=0;p<room.numInhabitants();p++) <add> { <add> M=room.fetchInhabitant(p); <add> if(M!=monster) <add> { <add> HashSet seen=new HashSet(); <add> while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) <add> { <add> seen.add(M); <add> M=M.amFollowing(); <add> } <add> choices.addElement(M); <add> } <add> } <add> if(choices.size() > 0) <add> tmp[11] = choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); <add> } <add> } <add> return (MOB)tmp[11]; <ide> } <ide> <ide> public String execute(Environmental scripted, <ide> if(Tool==null) Tool=defaultItem; <ide> String resp=null; <ide> if(msg.target() instanceof MOB) <del> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[10]); <add> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[12]); <ide> else <ide> if(msg.target() instanceof Item) <del> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,new Object[10]); <del> else <del> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[10]); <add> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,new Object[12]); <add> else <add> resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,new Object[12]); <ide> if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL"))) <ide> return false; <ide> } <ide> if(lastMsg==msg) break; <ide> lastMsg=msg; <ide> if(msg.target() instanceof Coins) <del> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); <ide> return; <ide> if(lastMsg==msg) break; <ide> lastMsg=msg; <ide> if(msg.target() instanceof Coins) <del> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,null)); <ide> return; <ide> if(lastMsg==msg) break; <ide> lastMsg=msg; <ide> if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); <ide> return; <ide> if(lastMsg==msg) break; <ide> lastMsg=msg; <ide> if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),(Item)msg.tool(),script,1,null)); <ide> return; <ide> Item product=makeCheapItem(msg.tool()); <ide> if((product instanceof Coins) <ide> &&(product.owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); <ide> return; <ide> Item product=makeCheapItem(msg.tool()); <ide> if((product instanceof Coins) <ide> &&(product.owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); <ide> return; <ide> Item product=makeCheapItem(msg.tool()); <ide> if((product instanceof Coins) <ide> &&(product.owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); <ide> return; <ide> Item product=makeCheapItem(msg.tool()); <ide> if((product instanceof Coins) <ide> &&(product.owner() instanceof Room)) <del> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[10]); <add> execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,new Object[12]); <ide> else <ide> que.addElement(new ScriptableResponse(affecting,msg.source(),monster,monster,product,product,script,1,null)); <ide> return; <ide> src=(MOB)msg.tool(); <ide> if((src==null)||(src.location()!=monster.location())) <ide> src=ded; <del> execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[12]); <ide> return; <ide> } <ide> break; <ide> src=(MOB)msg.tool(); <ide> if((src==null)||(src.location()!=monster.location())) <ide> src=ded; <del> execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,src,ded,ded,defaultItem,null,script,null,new Object[12]); <ide> return; <ide> } <ide> break; <ide> Item I=null; <ide> if(msg.tool() instanceof Item) <ide> I=(Item)msg.tool(); <del> execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),new Object[10]); <add> execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),new Object[12]); <ide> return; <ide> } <ide> break; <ide> { <ide> int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); <ide> if(CMLib.dice().rollPercentage()<prcnt) <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> break; <ide> case 16: // delay_prog <ide> delayProgCounters.put(new Integer(thisScriptIndex),new Integer(0)); <ide> if(delayProgCounter==targetTick) <ide> { <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> delayProgCounter=-1; <ide> } <ide> delayProgCounters.remove(new Integer(thisScriptIndex)); <ide> { <ide> int prcnt=CMath.s_int(CMParms.getCleanBit(trigger,1).trim()); <ide> if(CMLib.dice().rollPercentage()<prcnt) <del> execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> else <ide> if((ticking instanceof Item) <ide> { <ide> MOB M=(MOB)((Item)ticking).owner(); <ide> if(!M.amDead()) <del> execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> } <ide> break; <ide> { <ide> int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),mob.maxState().getHitPoints())); <ide> if(mob.curState().getHitPoints()<=floor) <del> execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> else <ide> if((ticking instanceof Item) <ide> { <ide> int floor=(int)Math.round(CMath.mul(CMath.div(CMath.s_int(CMParms.getCleanBit(trigger,1).trim()),100.0),M.maxState().getHitPoints())); <ide> if(M.curState().getHitPoints()<=floor) <del> execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> } <ide> break; <ide> if(!oncesDone.contains(script)&&canTrigger(6)) <ide> { <ide> oncesDone.addElement(script); <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> break; <ide> case 14: // time_prog <ide> if(time==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) <ide> { <ide> done=true; <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> lastTimeProgsDone.remove(new Integer(thisScriptIndex)); <ide> lastTimeProgsDone.put(new Integer(thisScriptIndex),new Integer(time)); <ide> break; <ide> if(day==CMath.s_int(CMParms.getCleanBit(trigger,i).trim())) <ide> { <ide> done=true; <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> lastDayProgsDone.remove(new Integer(thisScriptIndex)); <ide> lastDayProgsDone.put(new Integer(thisScriptIndex),new Integer(day)); <ide> break; <ide> if(time>=Q.minsRemaining()) <ide> { <ide> oncesDone.addElement(script); <del> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[10]); <add> execute(affecting,mob,mob,mob,defaultItem,null,script,null,new Object[12]); <ide> } <ide> } <ide> } <ide> try{SB=(ScriptableResponse)que.elementAt(q);}catch(ArrayIndexOutOfBoundsException x){continue;} <ide> if(SB.checkTimeToExecute()) <ide> { <del> execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,new Object[10]); <add> execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,new Object[12]); <ide> que.removeElement(SB); <ide> } <ide> }
Java
apache-2.0
9a36e78a6e8df647eea4f61ac2f24ef2f376685c
0
MikkelTAndersen/libgdx,anserran/libgdx,firefly2442/libgdx,jsjolund/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,hyvas/libgdx,SidneyXu/libgdx,sarkanyi/libgdx,kotcrab/libgdx,josephknight/libgdx,jsjolund/libgdx,jberberick/libgdx,nrallakis/libgdx,anserran/libgdx,kotcrab/libgdx,xoppa/libgdx,bsmr-java/libgdx,jberberick/libgdx,sarkanyi/libgdx,firefly2442/libgdx,ttencate/libgdx,realitix/libgdx,kotcrab/libgdx,anserran/libgdx,MovingBlocks/libgdx,czyzby/libgdx,js78/libgdx,JFixby/libgdx,BlueRiverInteractive/libgdx,xoppa/libgdx,toa5/libgdx,hyvas/libgdx,tommyettinger/libgdx,samskivert/libgdx,xoppa/libgdx,Dzamir/libgdx,MovingBlocks/libgdx,codepoke/libgdx,BlueRiverInteractive/libgdx,sarkanyi/libgdx,MikkelTAndersen/libgdx,Dzamir/libgdx,FredGithub/libgdx,toa5/libgdx,Dzamir/libgdx,josephknight/libgdx,sarkanyi/libgdx,josephknight/libgdx,samskivert/libgdx,alex-dorokhov/libgdx,xoppa/libgdx,bsmr-java/libgdx,gouessej/libgdx,realitix/libgdx,bladecoder/libgdx,bsmr-java/libgdx,FredGithub/libgdx,FredGithub/libgdx,codepoke/libgdx,josephknight/libgdx,libgdx/libgdx,hyvas/libgdx,alex-dorokhov/libgdx,BlueRiverInteractive/libgdx,bsmr-java/libgdx,stinsonga/libgdx,samskivert/libgdx,Xhanim/libgdx,MovingBlocks/libgdx,libgdx/libgdx,MadcowD/libgdx,xoppa/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,Dzamir/libgdx,SidneyXu/libgdx,BlueRiverInteractive/libgdx,cypherdare/libgdx,yangweigbh/libgdx,Dzamir/libgdx,JFixby/libgdx,nrallakis/libgdx,fwolff/libgdx,toa5/libgdx,Dzamir/libgdx,firefly2442/libgdx,toa5/libgdx,FredGithub/libgdx,realitix/libgdx,gouessej/libgdx,Thotep/libgdx,yangweigbh/libgdx,SidneyXu/libgdx,js78/libgdx,Dzamir/libgdx,Xhanim/libgdx,codepoke/libgdx,bgroenks96/libgdx,stinsonga/libgdx,tommyettinger/libgdx,yangweigbh/libgdx,czyzby/libgdx,Thotep/libgdx,Xhanim/libgdx,xoppa/libgdx,libgdx/libgdx,samskivert/libgdx,js78/libgdx,samskivert/libgdx,bgroenks96/libgdx,bgroenks96/libgdx,BlueRiverInteractive/libgdx,stinsonga/libgdx,bladecoder/libgdx,js78/libgdx,sarkanyi/libgdx,MikkelTAndersen/libgdx,ttencate/libgdx,stinsonga/libgdx,czyzby/libgdx,MadcowD/libgdx,fwolff/libgdx,nrallakis/libgdx,Thotep/libgdx,JFixby/libgdx,hyvas/libgdx,jsjolund/libgdx,NathanSweet/libgdx,ttencate/libgdx,codepoke/libgdx,gouessej/libgdx,bladecoder/libgdx,gouessej/libgdx,js78/libgdx,yangweigbh/libgdx,bsmr-java/libgdx,kotcrab/libgdx,josephknight/libgdx,MovingBlocks/libgdx,MadcowD/libgdx,czyzby/libgdx,Thotep/libgdx,MadcowD/libgdx,JFixby/libgdx,bgroenks96/libgdx,BlueRiverInteractive/libgdx,fwolff/libgdx,tommyettinger/libgdx,realitix/libgdx,czyzby/libgdx,codepoke/libgdx,bsmr-java/libgdx,SidneyXu/libgdx,anserran/libgdx,Dzamir/libgdx,Zomby2D/libgdx,hyvas/libgdx,JFixby/libgdx,kotcrab/libgdx,NathanSweet/libgdx,bladecoder/libgdx,SidneyXu/libgdx,toa5/libgdx,yangweigbh/libgdx,toa5/libgdx,JFixby/libgdx,jberberick/libgdx,fwolff/libgdx,Zomby2D/libgdx,SidneyXu/libgdx,bgroenks96/libgdx,js78/libgdx,kotcrab/libgdx,bgroenks96/libgdx,bsmr-java/libgdx,cypherdare/libgdx,cypherdare/libgdx,MikkelTAndersen/libgdx,Xhanim/libgdx,anserran/libgdx,josephknight/libgdx,samskivert/libgdx,samskivert/libgdx,hyvas/libgdx,nrallakis/libgdx,bsmr-java/libgdx,alex-dorokhov/libgdx,alex-dorokhov/libgdx,bgroenks96/libgdx,BlueRiverInteractive/libgdx,FredGithub/libgdx,bladecoder/libgdx,MadcowD/libgdx,Thotep/libgdx,codepoke/libgdx,josephknight/libgdx,Thotep/libgdx,MikkelTAndersen/libgdx,MikkelTAndersen/libgdx,FredGithub/libgdx,tommyettinger/libgdx,SidneyXu/libgdx,libgdx/libgdx,js78/libgdx,gouessej/libgdx,czyzby/libgdx,fwolff/libgdx,jsjolund/libgdx,samskivert/libgdx,js78/libgdx,alex-dorokhov/libgdx,fwolff/libgdx,cypherdare/libgdx,jberberick/libgdx,NathanSweet/libgdx,cypherdare/libgdx,NathanSweet/libgdx,fwolff/libgdx,sarkanyi/libgdx,MadcowD/libgdx,toa5/libgdx,realitix/libgdx,czyzby/libgdx,Zomby2D/libgdx,realitix/libgdx,Thotep/libgdx,jsjolund/libgdx,nrallakis/libgdx,Zomby2D/libgdx,jsjolund/libgdx,codepoke/libgdx,czyzby/libgdx,MadcowD/libgdx,firefly2442/libgdx,hyvas/libgdx,xoppa/libgdx,FredGithub/libgdx,Xhanim/libgdx,MadcowD/libgdx,jsjolund/libgdx,alex-dorokhov/libgdx,codepoke/libgdx,gouessej/libgdx,NathanSweet/libgdx,BlueRiverInteractive/libgdx,realitix/libgdx,gouessej/libgdx,hyvas/libgdx,Xhanim/libgdx,tommyettinger/libgdx,ttencate/libgdx,jberberick/libgdx,bgroenks96/libgdx,josephknight/libgdx,ttencate/libgdx,SidneyXu/libgdx,ttencate/libgdx,Zomby2D/libgdx,anserran/libgdx,yangweigbh/libgdx,MikkelTAndersen/libgdx,stinsonga/libgdx,MovingBlocks/libgdx,firefly2442/libgdx,MovingBlocks/libgdx,Xhanim/libgdx,JFixby/libgdx,MovingBlocks/libgdx,fwolff/libgdx,realitix/libgdx,firefly2442/libgdx,xoppa/libgdx,firefly2442/libgdx,yangweigbh/libgdx,jberberick/libgdx,JFixby/libgdx,yangweigbh/libgdx,jberberick/libgdx,kotcrab/libgdx,libgdx/libgdx,nrallakis/libgdx,ttencate/libgdx,Xhanim/libgdx,jberberick/libgdx,nrallakis/libgdx,anserran/libgdx,MovingBlocks/libgdx,kotcrab/libgdx,Thotep/libgdx,MikkelTAndersen/libgdx,gouessej/libgdx,anserran/libgdx,jsjolund/libgdx,firefly2442/libgdx,nrallakis/libgdx,FredGithub/libgdx,toa5/libgdx,ttencate/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d; import static com.badlogic.gdx.utils.Align.*; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent.Type; import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.DelayedRemovalArray; import com.badlogic.gdx.utils.Pools; /** 2D scene graph node. An actor has a position, rectangular size, origin, scale, rotation, Z index, and color. The position * corresponds to the unrotated, unscaled bottom left corner of the actor. The position is relative to the actor's parent. The * origin is relative to the position and is used for scale and rotation. * <p> * An actor has a list of in progress {@link Action actions} that are applied to the actor (often over time). These are generally * used to change the presentation of the actor (moving it, resizing it, etc). See {@link #act(float)}, {@link Action} and its * many subclasses. * <p> * An actor has two kinds of listeners associated with it: "capture" and regular. The listeners are notified of events the actor * or its children receive. The regular listeners are designed to allow an actor to respond to events that have been delivered. * The capture listeners are designed to allow a parent or container actor to handle events before child actors. See {@link #fire} * for more details. * <p> * An {@link InputListener} can receive all the basic input events. More complex listeners (like {@link ClickListener} and * {@link ActorGestureListener}) can listen for and combine primitive events and recognize complex interactions like multi-touch * or pinch. * @author mzechner * @author Nathan Sweet */ public class Actor { private Stage stage; Group parent; private final DelayedRemovalArray<EventListener> listeners = new DelayedRemovalArray(0); private final DelayedRemovalArray<EventListener> captureListeners = new DelayedRemovalArray(0); private final Array<Action> actions = new Array(0); private String name; private Touchable touchable = Touchable.enabled; private boolean visible = true, debug; float x, y; float width, height; float originX, originY; float scaleX = 1, scaleY = 1; float rotation; final Color color = new Color(1, 1, 1, 1); private Object userObject; /** Draws the actor. The batch is configured to draw in the parent's coordinate system. * {@link Batch#draw(com.badlogic.gdx.graphics.g2d.TextureRegion, float, float, float, float, float, float, float, float, float) * This draw method} is convenient to draw a rotated and scaled TextureRegion. {@link Batch#begin()} has already been called on * the batch. If {@link Batch#end()} is called to draw without the batch then {@link Batch#begin()} must be called before the * method returns. * <p> * The default implementation does nothing. * @param parentAlpha Should be multiplied with the actor's alpha, allowing a parent's alpha to affect all children. */ public void draw (Batch batch, float parentAlpha) { } /** Updates the actor based on time. Typically this is called each frame by {@link Stage#act(float)}. * <p> * The default implementation calls {@link Action#act(float)} on each action and removes actions that are complete. * @param delta Time in seconds since the last frame. */ public void act (float delta) { Array<Action> actions = this.actions; if (actions.size > 0) { if (stage != null && stage.getActionsRequestRendering()) Gdx.graphics.requestRendering(); for (int i = 0; i < actions.size; i++) { Action action = actions.get(i); if (action.act(delta) && i < actions.size) { Action current = actions.get(i); int actionIndex = current == action ? i : actions.indexOf(action, true); if (actionIndex != -1) { actions.removeIndex(actionIndex); action.setActor(null); i--; } } } } } /** Sets this actor as the event {@link Event#setTarget(Actor) target} and propagates the event to this actor and ancestor * actors as necessary. If this actor is not in the stage, the stage must be set before calling this method. * <p> * Events are fired in 2 phases: * <ol> * <li>The first phase (the "capture" phase) notifies listeners on each actor starting at the root and propagating downward to * (and including) this actor.</li> * <li>The second phase notifies listeners on each actor starting at this actor and, if {@link Event#getBubbles()} is true, * propagating upward to the root.</li> * </ol> * If the event is {@link Event#stop() stopped} at any time, it will not propagate to the next actor. * @return true if the event was {@link Event#cancel() cancelled}. */ public boolean fire (Event event) { if (event.getStage() == null) event.setStage(getStage()); event.setTarget(this); // Collect ancestors so event propagation is unaffected by hierarchy changes. Array<Group> ancestors = Pools.obtain(Array.class); Group parent = this.parent; while (parent != null) { ancestors.add(parent); parent = parent.parent; } try { // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it. Object[] ancestorsArray = ancestors.items; for (int i = ancestors.size - 1; i >= 0; i--) { Group currentTarget = (Group)ancestorsArray[i]; currentTarget.notify(event, true); if (event.isStopped()) return event.isCancelled(); } // Notify the target capture listeners. notify(event, true); if (event.isStopped()) return event.isCancelled(); // Notify the target listeners. notify(event, false); if (!event.getBubbles()) return event.isCancelled(); if (event.isStopped()) return event.isCancelled(); // Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it. for (int i = 0, n = ancestors.size; i < n; i++) { ((Group)ancestorsArray[i]).notify(event, false); if (event.isStopped()) return event.isCancelled(); } return event.isCancelled(); } finally { ancestors.clear(); Pools.free(ancestors); } } /** Notifies this actor's listeners of the event. The event is not propagated to any parents. Before notifying the listeners, * this actor is set as the {@link Event#getListenerActor() listener actor}. The event {@link Event#setTarget(Actor) target} * must be set before calling this method. If this actor is not in the stage, the stage must be set before calling this method. * @param capture If true, the capture listeners will be notified instead of the regular listeners. * @return true of the event was {@link Event#cancel() cancelled}. */ public boolean notify (Event event, boolean capture) { if (event.getTarget() == null) throw new IllegalArgumentException("The event target cannot be null."); DelayedRemovalArray<EventListener> listeners = capture ? captureListeners : this.listeners; if (listeners.size == 0) return event.isCancelled(); event.setListenerActor(this); event.setCapture(capture); if (event.getStage() == null) event.setStage(stage); listeners.begin(); for (int i = 0, n = listeners.size; i < n; i++) { EventListener listener = listeners.get(i); if (listener.handle(event)) { event.handle(); if (event instanceof InputEvent) { InputEvent inputEvent = (InputEvent)event; if (inputEvent.getType() == Type.touchDown) { event.getStage().addTouchFocus(listener, this, inputEvent.getTarget(), inputEvent.getPointer(), inputEvent.getButton()); } } } } listeners.end(); return event.isCancelled(); } /** Returns the deepest actor that contains the specified point and is {@link #getTouchable() touchable} and * {@link #isVisible() visible}, or null if no actor was hit. The point is specified in the actor's local coordinate system * (0,0 is the bottom left of the actor and width,height is the upper right). * <p> * This method is used to delegate touchDown, mouse, and enter/exit events. If this method returns null, those events will not * occur on this Actor. * <p> * The default implementation returns this actor if the point is within this actor's bounds. * @param touchable If true, the hit detection will respect the {@link #setTouchable(Touchable) touchability}. * @see Touchable */ public Actor hit (float x, float y, boolean touchable) { if (touchable && this.touchable != Touchable.enabled) return null; return x >= 0 && x < width && y >= 0 && y < height ? this : null; } /** Removes this actor from its parent, if it has a parent. * @see Group#removeActor(Actor) */ public boolean remove () { if (parent != null) return parent.removeActor(this, true); return false; } /** Add a listener to receive events that {@link #hit(float, float, boolean) hit} this actor. See {@link #fire(Event)}. * @see InputListener * @see ClickListener */ public boolean addListener (EventListener listener) { if (!listeners.contains(listener, true)) { listeners.add(listener); return true; } return false; } public boolean removeListener (EventListener listener) { return listeners.removeValue(listener, true); } public Array<EventListener> getListeners () { return listeners; } /** Adds a listener that is only notified during the capture phase. * @see #fire(Event) */ public boolean addCaptureListener (EventListener listener) { if (!captureListeners.contains(listener, true)) captureListeners.add(listener); return true; } public boolean removeCaptureListener (EventListener listener) { return captureListeners.removeValue(listener, true); } public Array<EventListener> getCaptureListeners () { return captureListeners; } public void addAction (Action action) { action.setActor(this); actions.add(action); if (stage != null && stage.getActionsRequestRendering()) Gdx.graphics.requestRendering(); } public void removeAction (Action action) { if (actions.removeValue(action, true)) action.setActor(null); } public Array<Action> getActions () { return actions; } /** Returns true if the actor has one or more actions. */ public boolean hasActions () { return actions.size > 0; } /** Removes all actions on this actor. */ public void clearActions () { for (int i = actions.size - 1; i >= 0; i--) actions.get(i).setActor(null); actions.clear(); } /** Removes all listeners on this actor. */ public void clearListeners () { listeners.clear(); captureListeners.clear(); } /** Removes all actions and listeners on this actor. */ public void clear () { clearActions(); clearListeners(); } /** Returns the stage that this actor is currently in, or null if not in a stage. */ public Stage getStage () { return stage; } /** Called by the framework when this actor or any parent is added to a group that is in the stage. * @param stage May be null if the actor or any parent is no longer in a stage. */ protected void setStage (Stage stage) { this.stage = stage; } /** Returns true if this actor is the same as or is the descendant of the specified actor. */ public boolean isDescendantOf (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); Actor parent = this; while (true) { if (parent == null) return false; if (parent == actor) return true; parent = parent.parent; } } /** Returns true if this actor is the same as or is the ascendant of the specified actor. */ public boolean isAscendantOf (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); while (true) { if (actor == null) return false; if (actor == this) return true; actor = actor.parent; } } /** Returns true if the actor's parent is not null. */ public boolean hasParent () { return parent != null; } /** Returns the parent actor, or null if not in a group. */ public Group getParent () { return parent; } /** Called by the framework when an actor is added to or removed from a group. * @param parent May be null if the actor has been removed from the parent. */ protected void setParent (Group parent) { this.parent = parent; } /** Returns true if input events are processed by this actor. */ public boolean isTouchable () { return touchable == Touchable.enabled; } public Touchable getTouchable () { return touchable; } /** Determines how touch events are distributed to this actor. Default is {@link Touchable#enabled}. */ public void setTouchable (Touchable touchable) { this.touchable = touchable; } public boolean isVisible () { return visible; } /** If false, the actor will not be drawn and will not receive touch events. Default is true. */ public void setVisible (boolean visible) { this.visible = visible; } /** Returns an application specific object for convenience, or null. */ public Object getUserObject () { return userObject; } /** Sets an application specific object for convenience. */ public void setUserObject (Object userObject) { this.userObject = userObject; } /** Returns the X position of the actor's left edge. */ public float getX () { return x; } /** Returns the X position of the specified {@link Align alignment}. */ public float getX (int alignment) { float x = this.x; if ((alignment & right) != 0) x += width; else if ((alignment & left) == 0) // x += width / 2; return x; } public void setX (float x) { if (this.x != x) { this.x = x; positionChanged(); } } /** Returns the Y position of the actor's bottom edge. */ public float getY () { return y; } public void setY (float y) { if (this.y != y) { this.y = y; positionChanged(); } } /** Returns the Y position of the specified {@link Align alignment}. */ public float getY (int alignment) { float y = this.y; if ((alignment & top) != 0) y += height; else if ((alignment & bottom) == 0) // y += height / 2; return y; } /** Sets the position of the actor's bottom left corner. */ public void setPosition (float x, float y) { if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } } /** Sets the position using the specified {@link Align alignment}. Note this may set the position to non-integer * coordinates. */ public void setPosition (float x, float y, int alignment) { if ((alignment & right) != 0) x -= width; else if ((alignment & left) == 0) // x -= width / 2; if ((alignment & top) != 0) y -= height; else if ((alignment & bottom) == 0) // y -= height / 2; if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } } /** Add x and y to current position */ public void moveBy (float x, float y) { if (x != 0 || y != 0) { this.x += x; this.y += y; positionChanged(); } } public float getWidth () { return width; } public void setWidth (float width) { if (this.width != width) { this.width = width; sizeChanged(); } } public float getHeight () { return height; } public void setHeight (float height) { if (this.height != height) { this.height = height; sizeChanged(); } } /** Returns y plus height. */ public float getTop () { return y + height; } /** Returns x plus width. */ public float getRight () { return x + width; } /** Called when the actor's position has been changed. */ protected void positionChanged () { } /** Called when the actor's size has been changed. */ protected void sizeChanged () { } /** Called when the actor's rotation has been changed. */ protected void rotationChanged () { } /** Sets the width and height. */ public void setSize (float width, float height) { if (this.width != width || this.height != height) { this.width = width; this.height = height; sizeChanged(); } } /** Adds the specified size to the current size. */ public void sizeBy (float size) { if (size != 0) { width += size; height += size; sizeChanged(); } } /** Adds the specified size to the current size. */ public void sizeBy (float width, float height) { if (width != 0 || height != 0) { this.width += width; this.height += height; sizeChanged(); } } /** Set bounds the x, y, width, and height. */ public void setBounds (float x, float y, float width, float height) { if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } if (this.width != width || this.height != height) { this.width = width; this.height = height; sizeChanged(); } } public float getOriginX () { return originX; } public void setOriginX (float originX) { this.originX = originX; } public float getOriginY () { return originY; } public void setOriginY (float originY) { this.originY = originY; } /** Sets the origin position which is relative to the actor's bottom left corner. */ public void setOrigin (float originX, float originY) { this.originX = originX; this.originY = originY; } /** Sets the origin position to the specified {@link Align alignment}. */ public void setOrigin (int alignment) { if ((alignment & left) != 0) originX = 0; else if ((alignment & right) != 0) originX = width; else originX = width / 2; if ((alignment & bottom) != 0) originY = 0; else if ((alignment & top) != 0) originY = height; else originY = height / 2; } public float getScaleX () { return scaleX; } public void setScaleX (float scaleX) { this.scaleX = scaleX; } public float getScaleY () { return scaleY; } public void setScaleY (float scaleY) { this.scaleY = scaleY; } /** Sets the scale for both X and Y */ public void setScale (float scaleXY) { this.scaleX = scaleXY; this.scaleY = scaleXY; } /** Sets the scale X and scale Y. */ public void setScale (float scaleX, float scaleY) { this.scaleX = scaleX; this.scaleY = scaleY; } /** Adds the specified scale to the current scale. */ public void scaleBy (float scale) { scaleX += scale; scaleY += scale; } /** Adds the specified scale to the current scale. */ public void scaleBy (float scaleX, float scaleY) { this.scaleX += scaleX; this.scaleY += scaleY; } public float getRotation () { return rotation; } public void setRotation (float degrees) { if (this.rotation != degrees) { this.rotation = degrees; rotationChanged(); } } /** Adds the specified rotation to the current rotation. */ public void rotateBy (float amountInDegrees) { if (amountInDegrees != 0) { rotation += amountInDegrees; rotationChanged(); } } public void setColor (Color color) { this.color.set(color); } public void setColor (float r, float g, float b, float a) { color.set(r, g, b, a); } /** Returns the color the actor will be tinted when drawn. The returned instance can be modified to change the color. */ public Color getColor () { return color; } /** @see #setName(String) * @return May be null. */ public String getName () { return name; } /** Set the actor's name, which is used for identification convenience and by {@link #toString()}. * @param name May be null. * @see Group#findActor(String) */ public void setName (String name) { this.name = name; } /** Changes the z-order for this actor so it is in front of all siblings. */ public void toFront () { setZIndex(Integer.MAX_VALUE); } /** Changes the z-order for this actor so it is in back of all siblings. */ public void toBack () { setZIndex(0); } /** Sets the z-index of this actor. The z-index is the index into the parent's {@link Group#getChildren() children}, where a * lower index is below a higher index. Setting a z-index higher than the number of children will move the child to the front. * Setting a z-index less than zero is invalid. */ public void setZIndex (int index) { if (index < 0) throw new IllegalArgumentException("ZIndex cannot be < 0."); Group parent = this.parent; if (parent == null) return; Array<Actor> children = parent.children; if (children.size == 1) return; index = Math.min(index, children.size - 1); if (index == children.indexOf(this, true)) return; if (!children.removeValue(this, true)) return; children.insert(index, this); } /** Returns the z-index of this actor. * @see #setZIndex(int) */ public int getZIndex () { Group parent = this.parent; if (parent == null) return -1; return parent.children.indexOf(this, true); } /** Calls {@link #clipBegin(float, float, float, float)} to clip this actor's bounds. */ public boolean clipBegin () { return clipBegin(x, y, width, height); } /** Clips the specified screen aligned rectangle, specified relative to the transform matrix of the stage's Batch. The * transform matrix and the stage's camera must not have rotational components. Calling this method must be followed by a call * to {@link #clipEnd()} if true is returned. * @return false if the clipping area is zero and no drawing should occur. * @see ScissorStack */ public boolean clipBegin (float x, float y, float width, float height) { if (width <= 0 || height <= 0) return false; Rectangle tableBounds = Rectangle.tmp; tableBounds.x = x; tableBounds.y = y; tableBounds.width = width; tableBounds.height = height; Stage stage = this.stage; Rectangle scissorBounds = Pools.obtain(Rectangle.class); stage.calculateScissors(tableBounds, scissorBounds); if (ScissorStack.pushScissors(scissorBounds)) return true; Pools.free(scissorBounds); return false; } /** Ends clipping begun by {@link #clipBegin(float, float, float, float)}. */ public void clipEnd () { Pools.free(ScissorStack.popScissors()); } /** Transforms the specified point in screen coordinates to the actor's local coordinate system. */ public Vector2 screenToLocalCoordinates (Vector2 screenCoords) { Stage stage = this.stage; if (stage == null) return screenCoords; return stageToLocalCoordinates(stage.screenToStageCoordinates(screenCoords)); } /** Transforms the specified point in the stage's coordinates to the actor's local coordinate system. */ public Vector2 stageToLocalCoordinates (Vector2 stageCoords) { if (parent != null) parent.stageToLocalCoordinates(stageCoords); parentToLocalCoordinates(stageCoords); return stageCoords; } /** Transforms the specified point in the actor's coordinates to be in the stage's coordinates. * @see Stage#toScreenCoordinates(Vector2, com.badlogic.gdx.math.Matrix4) */ public Vector2 localToStageCoordinates (Vector2 localCoords) { return localToAscendantCoordinates(null, localCoords); } /** Transforms the specified point in the actor's coordinates to be in the parent's coordinates. */ public Vector2 localToParentCoordinates (Vector2 localCoords) { final float rotation = -this.rotation; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final float x = this.x; final float y = this.y; if (rotation == 0) { if (scaleX == 1 && scaleY == 1) { localCoords.x += x; localCoords.y += y; } else { final float originX = this.originX; final float originY = this.originY; localCoords.x = (localCoords.x - originX) * scaleX + originX + x; localCoords.y = (localCoords.y - originY) * scaleY + originY + y; } } else { final float cos = (float)Math.cos(rotation * MathUtils.degreesToRadians); final float sin = (float)Math.sin(rotation * MathUtils.degreesToRadians); final float originX = this.originX; final float originY = this.originY; final float tox = (localCoords.x - originX) * scaleX; final float toy = (localCoords.y - originY) * scaleY; localCoords.x = (tox * cos + toy * sin) + originX + x; localCoords.y = (tox * -sin + toy * cos) + originY + y; } return localCoords; } /** Converts coordinates for this actor to those of a parent actor. The ascendant does not need to be a direct parent. */ public Vector2 localToAscendantCoordinates (Actor ascendant, Vector2 localCoords) { Actor actor = this; while (actor != null) { actor.localToParentCoordinates(localCoords); actor = actor.parent; if (actor == ascendant) break; } return localCoords; } /** Converts the coordinates given in the parent's coordinate system to this actor's coordinate system. */ public Vector2 parentToLocalCoordinates (Vector2 parentCoords) { final float rotation = this.rotation; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final float childX = x; final float childY = y; if (rotation == 0) { if (scaleX == 1 && scaleY == 1) { parentCoords.x -= childX; parentCoords.y -= childY; } else { final float originX = this.originX; final float originY = this.originY; parentCoords.x = (parentCoords.x - childX - originX) / scaleX + originX; parentCoords.y = (parentCoords.y - childY - originY) / scaleY + originY; } } else { final float cos = (float)Math.cos(rotation * MathUtils.degreesToRadians); final float sin = (float)Math.sin(rotation * MathUtils.degreesToRadians); final float originX = this.originX; final float originY = this.originY; final float tox = parentCoords.x - childX - originX; final float toy = parentCoords.y - childY - originY; parentCoords.x = (tox * cos + toy * sin) / scaleX + originX; parentCoords.y = (tox * -sin + toy * cos) / scaleY + originY; } return parentCoords; } /** Draws this actor's debug lines if {@link #getDebug()} is true. */ public void drawDebug (ShapeRenderer shapes) { drawDebugBounds(shapes); } /** Draws a rectange for the bounds of this actor if {@link #getDebug()} is true. */ protected void drawDebugBounds (ShapeRenderer shapes) { if (!debug) return; shapes.set(ShapeType.Line); shapes.setColor(stage.getDebugColor()); shapes.rect(x, y, originX, originY, width, height, scaleX, scaleY, rotation); } /** If true, {@link #drawDebug(ShapeRenderer)} will be called for this actor. */ public void setDebug (boolean enabled) { debug = enabled; if (enabled) Stage.debug = true; } public boolean getDebug () { return debug; } /** Calls {@link #setDebug(boolean)} with {@code true}. */ public Actor debug () { setDebug(true); return this; } public String toString () { String name = this.name; if (name == null) { name = getClass().getName(); int dotIndex = name.lastIndexOf('.'); if (dotIndex != -1) name = name.substring(dotIndex + 1); } return name; } }
gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d; import static com.badlogic.gdx.utils.Align.*; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent.Type; import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.DelayedRemovalArray; import com.badlogic.gdx.utils.Pools; /** 2D scene graph node. An actor has a position, rectangular size, origin, scale, rotation, Z index, and color. The position * corresponds to the unrotated, unscaled bottom left corner of the actor. The position is relative to the actor's parent. The * origin is relative to the position and is used for scale and rotation. * <p> * An actor has a list of in progress {@link Action actions} that are applied to the actor (often over time). These are generally * used to change the presentation of the actor (moving it, resizing it, etc). See {@link #act(float)}, {@link Action} and its * many subclasses. * <p> * An actor has two kinds of listeners associated with it: "capture" and regular. The listeners are notified of events the actor * or its children receive. The regular listeners are designed to allow an actor to respond to events that have been delivered. * The capture listeners are designed to allow a parent or container actor to handle events before child actors. See {@link #fire} * for more details. * <p> * An {@link InputListener} can receive all the basic input events. More complex listeners (like {@link ClickListener} and * {@link ActorGestureListener}) can listen for and combine primitive events and recognize complex interactions like multi-touch * or pinch. * @author mzechner * @author Nathan Sweet */ public class Actor { private Stage stage; Group parent; private final DelayedRemovalArray<EventListener> listeners = new DelayedRemovalArray(0); private final DelayedRemovalArray<EventListener> captureListeners = new DelayedRemovalArray(0); private final Array<Action> actions = new Array(0); private String name; private Touchable touchable = Touchable.enabled; private boolean visible = true, debug; float x, y; float width, height; float originX, originY; float scaleX = 1, scaleY = 1; float rotation; final Color color = new Color(1, 1, 1, 1); private Object userObject; /** Draws the actor. The batch is configured to draw in the parent's coordinate system. * {@link Batch#draw(com.badlogic.gdx.graphics.g2d.TextureRegion, float, float, float, float, float, float, float, float, float) * This draw method} is convenient to draw a rotated and scaled TextureRegion. {@link Batch#begin()} has already been called on * the batch. If {@link Batch#end()} is called to draw without the batch then {@link Batch#begin()} must be called before the * method returns. * <p> * The default implementation does nothing. * @param parentAlpha Should be multiplied with the actor's alpha, allowing a parent's alpha to affect all children. */ public void draw (Batch batch, float parentAlpha) { } /** Updates the actor based on time. Typically this is called each frame by {@link Stage#act(float)}. * <p> * The default implementation calls {@link Action#act(float)} on each action and removes actions that are complete. * @param delta Time in seconds since the last frame. */ public void act (float delta) { Array<Action> actions = this.actions; if (actions.size > 0) { if (stage != null && stage.getActionsRequestRendering()) Gdx.graphics.requestRendering(); for (int i = 0; i < actions.size; i++) { Action action = actions.get(i); if (action.act(delta) && i < actions.size) { Action current = actions.get(i); int actionIndex = current == action ? i : actions.indexOf(action, true); if (actionIndex != -1) { actions.removeIndex(actionIndex); action.setActor(null); i--; } } } } } /** Sets this actor as the event {@link Event#setTarget(Actor) target} and propagates the event to this actor and ancestor * actors as necessary. If this actor is not in the stage, the stage must be set before calling this method. * <p> * Events are fired in 2 phases. * <ol> * <li>The first phase (the "capture" phase) notifies listeners on each actor starting at the root and propagating downward to * (and including) this actor.</li> * <li>The second phase notifies listeners on each actor starting at this actor and, if {@link Event#getBubbles()} is true, * propagating upward to the root.</li> * </ol> * If the event is {@link Event#stop() stopped} at any time, it will not propagate to the next actor. * @return true if the event was {@link Event#cancel() cancelled}. */ public boolean fire (Event event) { if (event.getStage() == null) event.setStage(getStage()); event.setTarget(this); // Collect ancestors so event propagation is unaffected by hierarchy changes. Array<Group> ancestors = Pools.obtain(Array.class); Group parent = this.parent; while (parent != null) { ancestors.add(parent); parent = parent.parent; } try { // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it. Object[] ancestorsArray = ancestors.items; for (int i = ancestors.size - 1; i >= 0; i--) { Group currentTarget = (Group)ancestorsArray[i]; currentTarget.notify(event, true); if (event.isStopped()) return event.isCancelled(); } // Notify the target capture listeners. notify(event, true); if (event.isStopped()) return event.isCancelled(); // Notify the target listeners. notify(event, false); if (!event.getBubbles()) return event.isCancelled(); if (event.isStopped()) return event.isCancelled(); // Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it. for (int i = 0, n = ancestors.size; i < n; i++) { ((Group)ancestorsArray[i]).notify(event, false); if (event.isStopped()) return event.isCancelled(); } return event.isCancelled(); } finally { ancestors.clear(); Pools.free(ancestors); } } /** Notifies this actor's listeners of the event. The event is not propagated to any parents. Before notifying the listeners, * this actor is set as the {@link Event#getListenerActor() listener actor}. The event {@link Event#setTarget(Actor) target} * must be set before calling this method. If this actor is not in the stage, the stage must be set before calling this method. * @param capture If true, the capture listeners will be notified instead of the regular listeners. * @return true of the event was {@link Event#cancel() cancelled}. */ public boolean notify (Event event, boolean capture) { if (event.getTarget() == null) throw new IllegalArgumentException("The event target cannot be null."); DelayedRemovalArray<EventListener> listeners = capture ? captureListeners : this.listeners; if (listeners.size == 0) return event.isCancelled(); event.setListenerActor(this); event.setCapture(capture); if (event.getStage() == null) event.setStage(stage); listeners.begin(); for (int i = 0, n = listeners.size; i < n; i++) { EventListener listener = listeners.get(i); if (listener.handle(event)) { event.handle(); if (event instanceof InputEvent) { InputEvent inputEvent = (InputEvent)event; if (inputEvent.getType() == Type.touchDown) { event.getStage().addTouchFocus(listener, this, inputEvent.getTarget(), inputEvent.getPointer(), inputEvent.getButton()); } } } } listeners.end(); return event.isCancelled(); } /** Returns the deepest actor that contains the specified point and is {@link #getTouchable() touchable} and * {@link #isVisible() visible}, or null if no actor was hit. The point is specified in the actor's local coordinate system * (0,0 is the bottom left of the actor and width,height is the upper right). * <p> * This method is used to delegate touchDown, mouse, and enter/exit events. If this method returns null, those events will not * occur on this Actor. * <p> * The default implementation returns this actor if the point is within this actor's bounds. * @param touchable If true, the hit detection will respect the {@link #setTouchable(Touchable) touchability}. * @see Touchable */ public Actor hit (float x, float y, boolean touchable) { if (touchable && this.touchable != Touchable.enabled) return null; return x >= 0 && x < width && y >= 0 && y < height ? this : null; } /** Removes this actor from its parent, if it has a parent. * @see Group#removeActor(Actor) */ public boolean remove () { if (parent != null) return parent.removeActor(this, true); return false; } /** Add a listener to receive events that {@link #hit(float, float, boolean) hit} this actor. See {@link #fire(Event)}. * @see InputListener * @see ClickListener */ public boolean addListener (EventListener listener) { if (!listeners.contains(listener, true)) { listeners.add(listener); return true; } return false; } public boolean removeListener (EventListener listener) { return listeners.removeValue(listener, true); } public Array<EventListener> getListeners () { return listeners; } /** Adds a listener that is only notified during the capture phase. * @see #fire(Event) */ public boolean addCaptureListener (EventListener listener) { if (!captureListeners.contains(listener, true)) captureListeners.add(listener); return true; } public boolean removeCaptureListener (EventListener listener) { return captureListeners.removeValue(listener, true); } public Array<EventListener> getCaptureListeners () { return captureListeners; } public void addAction (Action action) { action.setActor(this); actions.add(action); if (stage != null && stage.getActionsRequestRendering()) Gdx.graphics.requestRendering(); } public void removeAction (Action action) { if (actions.removeValue(action, true)) action.setActor(null); } public Array<Action> getActions () { return actions; } /** Returns true if the actor has one or more actions. */ public boolean hasActions () { return actions.size > 0; } /** Removes all actions on this actor. */ public void clearActions () { for (int i = actions.size - 1; i >= 0; i--) actions.get(i).setActor(null); actions.clear(); } /** Removes all listeners on this actor. */ public void clearListeners () { listeners.clear(); captureListeners.clear(); } /** Removes all actions and listeners on this actor. */ public void clear () { clearActions(); clearListeners(); } /** Returns the stage that this actor is currently in, or null if not in a stage. */ public Stage getStage () { return stage; } /** Called by the framework when this actor or any parent is added to a group that is in the stage. * @param stage May be null if the actor or any parent is no longer in a stage. */ protected void setStage (Stage stage) { this.stage = stage; } /** Returns true if this actor is the same as or is the descendant of the specified actor. */ public boolean isDescendantOf (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); Actor parent = this; while (true) { if (parent == null) return false; if (parent == actor) return true; parent = parent.parent; } } /** Returns true if this actor is the same as or is the ascendant of the specified actor. */ public boolean isAscendantOf (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); while (true) { if (actor == null) return false; if (actor == this) return true; actor = actor.parent; } } /** Returns true if the actor's parent is not null. */ public boolean hasParent () { return parent != null; } /** Returns the parent actor, or null if not in a group. */ public Group getParent () { return parent; } /** Called by the framework when an actor is added to or removed from a group. * @param parent May be null if the actor has been removed from the parent. */ protected void setParent (Group parent) { this.parent = parent; } /** Returns true if input events are processed by this actor. */ public boolean isTouchable () { return touchable == Touchable.enabled; } public Touchable getTouchable () { return touchable; } /** Determines how touch events are distributed to this actor. Default is {@link Touchable#enabled}. */ public void setTouchable (Touchable touchable) { this.touchable = touchable; } public boolean isVisible () { return visible; } /** If false, the actor will not be drawn and will not receive touch events. Default is true. */ public void setVisible (boolean visible) { this.visible = visible; } /** Returns an application specific object for convenience, or null. */ public Object getUserObject () { return userObject; } /** Sets an application specific object for convenience. */ public void setUserObject (Object userObject) { this.userObject = userObject; } /** Returns the X position of the actor's left edge. */ public float getX () { return x; } /** Returns the X position of the specified {@link Align alignment}. */ public float getX (int alignment) { float x = this.x; if ((alignment & right) != 0) x += width; else if ((alignment & left) == 0) // x += width / 2; return x; } public void setX (float x) { if (this.x != x) { this.x = x; positionChanged(); } } /** Returns the Y position of the actor's bottom edge. */ public float getY () { return y; } public void setY (float y) { if (this.y != y) { this.y = y; positionChanged(); } } /** Returns the Y position of the specified {@link Align alignment}. */ public float getY (int alignment) { float y = this.y; if ((alignment & top) != 0) y += height; else if ((alignment & bottom) == 0) // y += height / 2; return y; } /** Sets the position of the actor's bottom left corner. */ public void setPosition (float x, float y) { if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } } /** Sets the position using the specified {@link Align alignment}. Note this may set the position to non-integer * coordinates. */ public void setPosition (float x, float y, int alignment) { if ((alignment & right) != 0) x -= width; else if ((alignment & left) == 0) // x -= width / 2; if ((alignment & top) != 0) y -= height; else if ((alignment & bottom) == 0) // y -= height / 2; if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } } /** Add x and y to current position */ public void moveBy (float x, float y) { if (x != 0 || y != 0) { this.x += x; this.y += y; positionChanged(); } } public float getWidth () { return width; } public void setWidth (float width) { if (this.width != width) { this.width = width; sizeChanged(); } } public float getHeight () { return height; } public void setHeight (float height) { if (this.height != height) { this.height = height; sizeChanged(); } } /** Returns y plus height. */ public float getTop () { return y + height; } /** Returns x plus width. */ public float getRight () { return x + width; } /** Called when the actor's position has been changed. */ protected void positionChanged () { } /** Called when the actor's size has been changed. */ protected void sizeChanged () { } /** Called when the actor's rotation has been changed. */ protected void rotationChanged () { } /** Sets the width and height. */ public void setSize (float width, float height) { if (this.width != width || this.height != height) { this.width = width; this.height = height; sizeChanged(); } } /** Adds the specified size to the current size. */ public void sizeBy (float size) { if (size != 0) { width += size; height += size; sizeChanged(); } } /** Adds the specified size to the current size. */ public void sizeBy (float width, float height) { if (width != 0 || height != 0) { this.width += width; this.height += height; sizeChanged(); } } /** Set bounds the x, y, width, and height. */ public void setBounds (float x, float y, float width, float height) { if (this.x != x || this.y != y) { this.x = x; this.y = y; positionChanged(); } if (this.width != width || this.height != height) { this.width = width; this.height = height; sizeChanged(); } } public float getOriginX () { return originX; } public void setOriginX (float originX) { this.originX = originX; } public float getOriginY () { return originY; } public void setOriginY (float originY) { this.originY = originY; } /** Sets the origin position which is relative to the actor's bottom left corner. */ public void setOrigin (float originX, float originY) { this.originX = originX; this.originY = originY; } /** Sets the origin position to the specified {@link Align alignment}. */ public void setOrigin (int alignment) { if ((alignment & left) != 0) originX = 0; else if ((alignment & right) != 0) originX = width; else originX = width / 2; if ((alignment & bottom) != 0) originY = 0; else if ((alignment & top) != 0) originY = height; else originY = height / 2; } public float getScaleX () { return scaleX; } public void setScaleX (float scaleX) { this.scaleX = scaleX; } public float getScaleY () { return scaleY; } public void setScaleY (float scaleY) { this.scaleY = scaleY; } /** Sets the scale for both X and Y */ public void setScale (float scaleXY) { this.scaleX = scaleXY; this.scaleY = scaleXY; } /** Sets the scale X and scale Y. */ public void setScale (float scaleX, float scaleY) { this.scaleX = scaleX; this.scaleY = scaleY; } /** Adds the specified scale to the current scale. */ public void scaleBy (float scale) { scaleX += scale; scaleY += scale; } /** Adds the specified scale to the current scale. */ public void scaleBy (float scaleX, float scaleY) { this.scaleX += scaleX; this.scaleY += scaleY; } public float getRotation () { return rotation; } public void setRotation (float degrees) { if (this.rotation != degrees) { this.rotation = degrees; rotationChanged(); } } /** Adds the specified rotation to the current rotation. */ public void rotateBy (float amountInDegrees) { if (amountInDegrees != 0) { rotation += amountInDegrees; rotationChanged(); } } public void setColor (Color color) { this.color.set(color); } public void setColor (float r, float g, float b, float a) { color.set(r, g, b, a); } /** Returns the color the actor will be tinted when drawn. The returned instance can be modified to change the color. */ public Color getColor () { return color; } /** @see #setName(String) * @return May be null. */ public String getName () { return name; } /** Set the actor's name, which is used for identification convenience and by {@link #toString()}. * @param name May be null. * @see Group#findActor(String) */ public void setName (String name) { this.name = name; } /** Changes the z-order for this actor so it is in front of all siblings. */ public void toFront () { setZIndex(Integer.MAX_VALUE); } /** Changes the z-order for this actor so it is in back of all siblings. */ public void toBack () { setZIndex(0); } /** Sets the z-index of this actor. The z-index is the index into the parent's {@link Group#getChildren() children}, where a * lower index is below a higher index. Setting a z-index higher than the number of children will move the child to the front. * Setting a z-index less than zero is invalid. */ public void setZIndex (int index) { if (index < 0) throw new IllegalArgumentException("ZIndex cannot be < 0."); Group parent = this.parent; if (parent == null) return; Array<Actor> children = parent.children; if (children.size == 1) return; index = Math.min(index, children.size - 1); if (index == children.indexOf(this, true)) return; if (!children.removeValue(this, true)) return; children.insert(index, this); } /** Returns the z-index of this actor. * @see #setZIndex(int) */ public int getZIndex () { Group parent = this.parent; if (parent == null) return -1; return parent.children.indexOf(this, true); } /** Calls {@link #clipBegin(float, float, float, float)} to clip this actor's bounds. */ public boolean clipBegin () { return clipBegin(x, y, width, height); } /** Clips the specified screen aligned rectangle, specified relative to the transform matrix of the stage's Batch. The * transform matrix and the stage's camera must not have rotational components. Calling this method must be followed by a call * to {@link #clipEnd()} if true is returned. * @return false if the clipping area is zero and no drawing should occur. * @see ScissorStack */ public boolean clipBegin (float x, float y, float width, float height) { if (width <= 0 || height <= 0) return false; Rectangle tableBounds = Rectangle.tmp; tableBounds.x = x; tableBounds.y = y; tableBounds.width = width; tableBounds.height = height; Stage stage = this.stage; Rectangle scissorBounds = Pools.obtain(Rectangle.class); stage.calculateScissors(tableBounds, scissorBounds); if (ScissorStack.pushScissors(scissorBounds)) return true; Pools.free(scissorBounds); return false; } /** Ends clipping begun by {@link #clipBegin(float, float, float, float)}. */ public void clipEnd () { Pools.free(ScissorStack.popScissors()); } /** Transforms the specified point in screen coordinates to the actor's local coordinate system. */ public Vector2 screenToLocalCoordinates (Vector2 screenCoords) { Stage stage = this.stage; if (stage == null) return screenCoords; return stageToLocalCoordinates(stage.screenToStageCoordinates(screenCoords)); } /** Transforms the specified point in the stage's coordinates to the actor's local coordinate system. */ public Vector2 stageToLocalCoordinates (Vector2 stageCoords) { if (parent != null) parent.stageToLocalCoordinates(stageCoords); parentToLocalCoordinates(stageCoords); return stageCoords; } /** Transforms the specified point in the actor's coordinates to be in the stage's coordinates. * @see Stage#toScreenCoordinates(Vector2, com.badlogic.gdx.math.Matrix4) */ public Vector2 localToStageCoordinates (Vector2 localCoords) { return localToAscendantCoordinates(null, localCoords); } /** Transforms the specified point in the actor's coordinates to be in the parent's coordinates. */ public Vector2 localToParentCoordinates (Vector2 localCoords) { final float rotation = -this.rotation; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final float x = this.x; final float y = this.y; if (rotation == 0) { if (scaleX == 1 && scaleY == 1) { localCoords.x += x; localCoords.y += y; } else { final float originX = this.originX; final float originY = this.originY; localCoords.x = (localCoords.x - originX) * scaleX + originX + x; localCoords.y = (localCoords.y - originY) * scaleY + originY + y; } } else { final float cos = (float)Math.cos(rotation * MathUtils.degreesToRadians); final float sin = (float)Math.sin(rotation * MathUtils.degreesToRadians); final float originX = this.originX; final float originY = this.originY; final float tox = (localCoords.x - originX) * scaleX; final float toy = (localCoords.y - originY) * scaleY; localCoords.x = (tox * cos + toy * sin) + originX + x; localCoords.y = (tox * -sin + toy * cos) + originY + y; } return localCoords; } /** Converts coordinates for this actor to those of a parent actor. The ascendant does not need to be a direct parent. */ public Vector2 localToAscendantCoordinates (Actor ascendant, Vector2 localCoords) { Actor actor = this; while (actor != null) { actor.localToParentCoordinates(localCoords); actor = actor.parent; if (actor == ascendant) break; } return localCoords; } /** Converts the coordinates given in the parent's coordinate system to this actor's coordinate system. */ public Vector2 parentToLocalCoordinates (Vector2 parentCoords) { final float rotation = this.rotation; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final float childX = x; final float childY = y; if (rotation == 0) { if (scaleX == 1 && scaleY == 1) { parentCoords.x -= childX; parentCoords.y -= childY; } else { final float originX = this.originX; final float originY = this.originY; parentCoords.x = (parentCoords.x - childX - originX) / scaleX + originX; parentCoords.y = (parentCoords.y - childY - originY) / scaleY + originY; } } else { final float cos = (float)Math.cos(rotation * MathUtils.degreesToRadians); final float sin = (float)Math.sin(rotation * MathUtils.degreesToRadians); final float originX = this.originX; final float originY = this.originY; final float tox = parentCoords.x - childX - originX; final float toy = parentCoords.y - childY - originY; parentCoords.x = (tox * cos + toy * sin) / scaleX + originX; parentCoords.y = (tox * -sin + toy * cos) / scaleY + originY; } return parentCoords; } /** Draws this actor's debug lines if {@link #getDebug()} is true. */ public void drawDebug (ShapeRenderer shapes) { drawDebugBounds(shapes); } /** Draws a rectange for the bounds of this actor if {@link #getDebug()} is true. */ protected void drawDebugBounds (ShapeRenderer shapes) { if (!debug) return; shapes.set(ShapeType.Line); shapes.setColor(stage.getDebugColor()); shapes.rect(x, y, originX, originY, width, height, scaleX, scaleY, rotation); } /** If true, {@link #drawDebug(ShapeRenderer)} will be called for this actor. */ public void setDebug (boolean enabled) { debug = enabled; if (enabled) Stage.debug = true; } public boolean getDebug () { return debug; } /** Calls {@link #setDebug(boolean)} with {@code true}. */ public Actor debug () { setDebug(true); return this; } public String toString () { String name = this.name; if (name == null) { name = getClass().getName(); int dotIndex = name.lastIndexOf('.'); if (dotIndex != -1) name = name.substring(dotIndex + 1); } return name; } }
Javadoc.
gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java
Javadoc.
<ide><path>dx/src/com/badlogic/gdx/scenes/scene2d/Actor.java <ide> /** Sets this actor as the event {@link Event#setTarget(Actor) target} and propagates the event to this actor and ancestor <ide> * actors as necessary. If this actor is not in the stage, the stage must be set before calling this method. <ide> * <p> <del> * Events are fired in 2 phases. <add> * Events are fired in 2 phases: <ide> * <ol> <ide> * <li>The first phase (the "capture" phase) notifies listeners on each actor starting at the root and propagating downward to <ide> * (and including) this actor.</li>
JavaScript
mit
cc2e64afb487609fe0f864fc2c554903e0fcd9fb
0
fsgiudice/quasar,pdanpdan/quasar,quasarframework/quasar,quasarframework/quasar,quasarframework/quasar,fsgiudice/quasar,rstoenescu/quasar-framework,pdanpdan/quasar,quasarframework/quasar,pdanpdan/quasar,rstoenescu/quasar-framework,rstoenescu/quasar-framework,pdanpdan/quasar,fsgiudice/quasar
import History from '../history.js' export default { props: { value: Boolean }, data () { return { showing: false } }, watch: { value (val) { if (this.disable === true && val === true) { this.$emit('input', false) return } if (val !== this.showing) { this[val ? 'show' : 'hide']() } } }, methods: { toggle (evt) { this[this.showing === true ? 'hide' : 'show'](evt) }, show (evt) { if (this.disable === true || this.showing === true) { return } if (this.__showCondition !== void 0 && this.__showCondition(evt) !== true) { return } this.$emit('before-show', evt) if (this.$q.platform.is.ie === true) { // IE sometimes performs a focus on body after click; // the delay prevents the click-outside to trigger on this focus setTimeout(() => { this.showing = true }, 0) } else { this.showing = true } this.$emit('input', true) if (this.$options.modelToggle !== void 0 && this.$options.modelToggle.history === true) { this.__historyEntry = { handler: this.hide } History.add(this.__historyEntry) } if (this.__show !== void 0) { this.__show(evt) } else { this.$emit('show', evt) } }, hide (evt) { if (this.disable === true || this.showing === false) { return } this.$emit('before-hide', evt) this.showing = false this.value !== false && this.$emit('input', false) this.__removeHistory() if (this.__hide !== void 0) { this.__hide(evt) } else { this.$emit('hide', evt) } }, __removeHistory () { if (this.__historyEntry !== void 0) { History.remove(this.__historyEntry) this.__historyEntry = void 0 } } }, beforeDestroy () { this.showing === true && this.__removeHistory() } }
ui/src/mixins/model-toggle.js
import History from '../history.js' export default { props: { value: Boolean }, data () { return { showing: false } }, watch: { value (val) { if (this.disable === true && val === true) { this.$emit('input', false) return } if (val !== this.showing) { this[val ? 'show' : 'hide']() } } }, methods: { toggle (evt) { this[this.showing === true ? 'hide' : 'show'](evt) }, show (evt) { if (this.disable === true || this.showing === true) { return } if (this.__showCondition !== void 0 && this.__showCondition(evt) !== true) { return } this.$emit('before-show', evt) this.showing = true this.$emit('input', true) if (this.$options.modelToggle !== void 0 && this.$options.modelToggle.history === true) { this.__historyEntry = { handler: this.hide } History.add(this.__historyEntry) } if (this.__show !== void 0) { this.__show(evt) } else { this.$emit('show', evt) } }, hide (evt) { if (this.disable === true || this.showing === false) { return } this.$emit('before-hide', evt) this.showing = false this.value !== false && this.$emit('input', false) this.__removeHistory() if (this.__hide !== void 0) { this.__hide(evt) } else { this.$emit('hide', evt) } }, __removeHistory () { if (this.__historyEntry !== void 0) { History.remove(this.__historyEntry) this.__historyEntry = void 0 } } }, beforeDestroy () { this.showing === true && this.__removeHistory() } }
fix(ie): Add a delay before setting showing because IE performs a refocus on body on click (#4213) * fix(ie): Add a delay before setting showing because IE performs a refocus on body on click ref #4208 * Update model-toggle.js
ui/src/mixins/model-toggle.js
fix(ie): Add a delay before setting showing because IE performs a refocus on body on click (#4213)
<ide><path>i/src/mixins/model-toggle.js <ide> } <ide> <ide> this.$emit('before-show', evt) <del> this.showing = true <add> <add> if (this.$q.platform.is.ie === true) { <add> // IE sometimes performs a focus on body after click; <add> // the delay prevents the click-outside to trigger on this focus <add> setTimeout(() => { <add> this.showing = true <add> }, 0) <add> } <add> else { <add> this.showing = true <add> } <add> <ide> this.$emit('input', true) <ide> <ide> if (this.$options.modelToggle !== void 0 && this.$options.modelToggle.history === true) {
Java
mit
b92896ac7db436b6cd53162b8dee3c6c022a3e02
0
rossdrew/emuRox,rossdrew/emuRox
package com.rox.emu.p6502; import com.rox.emu.Memory; import com.rox.emu.UnknownOpCodeException; /** * A emulated representation of MOS 6502, 8 bit * microprocessor functionality. * * @author Ross Drew */ public class CPU { private final Memory memory; private final Registers registers = new Registers(); public static final int CARRY_INDICATOR_BIT = 0x100; //The bit set on a word when a byte has carried up public static final int NEGATIVE_INDICATOR_BIT = 0x80; //The bit set on a byte when a it is negative public CPU(Memory memory) { this.memory = memory; } /** * IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it- */ public void reset(){ System.out.println("*** RESETTING >>>"); registers.setRegister(Registers.REG_ACCUMULATOR, 0x0); registers.setRegister(Registers.REG_X_INDEX, 0x0); registers.setRegister(Registers.REG_Y_INDEX, 0x0); registers.setRegister(Registers.REG_STATUS, 0x34); registers.setRegister(Registers.REG_PC_HIGH, memory.getByte(0xFFFC)); registers.setRegister(Registers.REG_PC_LOW, memory.getByte(0xFFFD)); registers.setRegister(Registers.REG_SP, 0xFF); System.out.println("...READY!"); } /** * Get the value of the 16 bit Program Counter (PC) and increment */ private int getAndStepPC(){ final int originalPC = registers.getPC(); registers.setPC(originalPC + 1); return originalPC; } private int getByteOfMemoryAt(int location, int index){ final int memoryByte = memory.getByte(location + index); System.out.println("FETCH mem[" + location + (index != 0 ? "[" + index + "]" : "") +"] --> " + memoryByte); return memoryByte; } private int setByteOfMemoryAt(int location, int index, int newByte){ memory.setByteAt(location + index, newByte); System.out.println("STORE " + newByte + " --> mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]"); return (location + index); } private int getByteOfMemoryXIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX)); } private int setByteOfMemoryXIndexedAt(int location, int newByte){ return setByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX), newByte); } private int getByteOfMemoryYIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_Y_INDEX)); } private int getByteOfMemoryAt(int location){ return getByteOfMemoryAt(location, 0); } public Registers getRegisters(){ return registers; } /** * Return the next byte from program memory, as defined * by the Program Counter. * <em>Increments the Program Counter by 1</em> * * @return byte from PC[0] */ private int nextProgramByte(){ int memoryLocation = getAndStepPC(); return getByteOfMemoryAt(memoryLocation); } /** * Combine the next two bytes in program memory, as defined by * the Program Counter into a word so that:- * * PC[0] = high order byte * PC[1] = low order byte * * <em>Increments the Program Counter by 1</em> * * @return word made up of both bytes */ private int nextProgramWord(){ int byte1 = nextProgramByte(); return (byte1 << 8) | nextProgramByte() ; } public void step(int steps){ for (int i=0; i<steps; i++) step(); } public void step() { System.out.println("\n*** STEP >>>"); int accumulatorBeforeOperation = registers.getRegister(Registers.REG_ACCUMULATOR); int opCode = nextProgramByte(); //Execute the opcode System.out.println("Instruction: " + InstructionSet.getOpCodeName(opCode) + "..."); switch (opCode){ case InstructionSet.OP_ASL_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR) << 1; setCarryFlagBasedOn(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte); } break; case InstructionSet.OP_ASL_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_Z_IX: { int location = nextProgramByte(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS_IX: { int location = nextProgramWord(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS: { int location = nextProgramWord(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_LSR_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR); setBorrowFlagFor(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte >> 1); } break; case InstructionSet.OP_LSR_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location); setBorrowFlagFor(newFakeByte); newFakeByte = newFakeByte >> 1; registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ROL_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROL(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_ROL_Z: int location = nextProgramByte(); memory.setByteAt(location, performROL(memory.getByte(location))); break; /* Not implemented and/or not published on older 6502s */ case InstructionSet.OP_ROR_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROR(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_SEC: registers.setFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLC: registers.clearFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLV: registers.clearFlag(Registers.STATUS_FLAG_OVERFLOW); break; case InstructionSet.OP_INC_Z: { int incrementLocation = nextProgramByte(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_INC_ABS: { int incrementLocation = nextProgramWord(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_DEC_Z: { int decrementLocation = nextProgramByte(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_DEC_ABS: { int decrementLocation = nextProgramWord(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_INX: registers.incrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_DEX: registers.decrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_INY: registers.incrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_DEY: registers.decrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_LDX_I: registers.setRegisterAndFlags(Registers.REG_X_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDY_I: registers.setRegisterAndFlags(Registers.REG_Y_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDA_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_LDA_IY: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte()); break; case InstructionSet.OP_LDA_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_LDA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_Z: performAND(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS: performAND(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_AND_I: performAND(nextProgramByte()); break; case InstructionSet.OP_AND_Z_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_BIT_Z: int memData = memory.getByte(nextProgramByte()); if ((memData & registers.getRegister(Registers.REG_ACCUMULATOR)) == memData) registers.setFlag(Registers.STATUS_FLAG_ZERO); else registers.clearFlag(Registers.STATUS_FLAG_ZERO); //Set N, V to bits 7 and 6 of memory data registers.setRegister(Registers.REG_STATUS, (memData & 0b11000000) | (registers.getRegister(Registers.REG_STATUS) & 0b00111111)); break; case InstructionSet.OP_ORA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() | accumulatorBeforeOperation); break; case InstructionSet.OP_ORA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) | accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() ^ accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) ^ accumulatorBeforeOperation); break; case InstructionSet.OP_ADC_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramByte()))); break; case InstructionSet.OP_ADC_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(nextProgramByte())); break; case InstructionSet.OP_ADC_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramWord()))); break; case InstructionSet.OP_ADC_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryXIndexedAt(nextProgramByte()))); break; //XXX Need to use 2s compliment addition (subtraction) // ? Do I deal with borrow in? does it need to manually set?! case InstructionSet.OP_CMP_I: int value = nextProgramByte(); int result = registers.getRegister(Registers.REG_ACCUMULATOR) - value; registers.setFlagsBasedOn(result & 0xFF); registers.setRegister(Registers.REG_ACCUMULATOR, result); break; case InstructionSet.OP_SBC_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(nextProgramByte())); break; case InstructionSet.OP_SBC_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(getByteOfMemoryAt(nextProgramByte()))); break; case InstructionSet.OP_STY_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_STA_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS: memory.setByteAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS_IX: setByteOfMemoryXIndexedAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STX_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_PHA: push(registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_PLA: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, pop()); break; case InstructionSet.OP_JMP_ABS: int h = nextProgramByte(); int l = nextProgramByte(); registers.setRegister(Registers.REG_PC_HIGH, h); registers.setRegister(Registers.REG_PC_LOW, l); break; case InstructionSet.OP_BCS: branchIf(registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BCC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BEQ: branchIf(registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BNE: branchIf(!registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BMI: branchIf(registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BPL: branchIf(!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BVS: branchIf(registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_BVC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_TAX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TAY: registers.setRegister(Registers.REG_Y_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TYA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_TXA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TXS: registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TSX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_SP)); registers.setFlagsBasedOn(registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_NOP: //Do nothing break; default: throw new UnknownOpCodeException("Unknown 6502 OpCode:" + opCode + " encountered.", opCode); } } private int pop(){ registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) + 1); int address = 0x0100 | registers.getRegister(Registers.REG_SP); return getByteOfMemoryAt(address); } private void push(int value){ memory.setByteAt(0x0100 | registers.getRegister(Registers.REG_SP), value); registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) - 1); } private int performROL(int initialValue){ int rotatedValue = (initialValue << 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); registers.setFlagsBasedOn(rotatedValue); setCarryFlagBasedOn(rotatedValue); return rotatedValue & 0xFF; } private int performROR(int initialValue){ int rotatedValue = (initialValue >> 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0b10000000 : 0); setBorrowFlagFor(initialValue); registers.setFlagsBasedOn(rotatedValue); return rotatedValue & 0xFF; } private void setBorrowFlagFor(int newFakeByte) { if ((newFakeByte & 0x1) == 0x1) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void setCarryFlagBasedOn(int newFakeByte) { if ((newFakeByte & CARRY_INDICATOR_BIT) == CARRY_INDICATOR_BIT) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void branchIf(boolean condition){ int location = nextProgramByte(); if (condition) branchTo(location); } /** * Branch to a relative location as defined by a signed byte * * @param displacement relative (-127 -> 128) location from end of branch instruction */ private void branchTo(int displacement) { int displacementByte = displacement & 0xFF; if ((displacementByte & NEGATIVE_INDICATOR_BIT) == NEGATIVE_INDICATOR_BIT) registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) - fromTwosComplimented(displacementByte)); else registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) + displacementByte); } private void performAND(int byteTerm){ registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, byteTerm & registers.getRegister(Registers.REG_ACCUMULATOR)); } private int performADC(int byteTerm){ int carry = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); return addToAccumulator(byteTerm + carry); } //(1) compliment of carry flag added (so subtracted) as well //(2) set carry if no borrow required (A >= M[v]) private int performSBC(int byteTerm){ registers.setFlag(Registers.STATUS_FLAG_NEGATIVE); int borrow = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0 : 1); return addToAccumulator(twosComplimentOf(byteTerm + borrow)); } private int twosComplimentOf(int byteValue){ return ((~byteValue) + 1) & 0xFF; } private int fromTwosComplimented(int byteValue){ return ((~byteValue)) & 0xFF; } /** * Perform a binary addition, setting Carry and Overflow flags as required. * * @param term term to add to the accumulator */ private int addToAccumulator(int term){ int result = registers.getRegister(Registers.REG_ACCUMULATOR) + term; //Set Carry, if bit 8 is set on new accumulator value, ignoring in 2s compliment addition (subtraction) if (!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)){ setCarryFlagBasedOn(result); }else { registers.clearFlag(Registers.STATUS_FLAG_CARRY); } //Set Overflow if the sign of both inputs is different from the sign of the result if (((registers.getRegister(Registers.REG_ACCUMULATOR) ^ result) & (term ^ result) & 0x80) != 0) registers.setFlag(Registers.STATUS_FLAG_OVERFLOW); return (result & 0xFF); } }
src/main/java/com/rox/emu/p6502/CPU.java
package com.rox.emu.p6502; import com.rox.emu.Memory; import com.rox.emu.UnknownOpCodeException; /** * A emulated representation of MOS 6502, 8 bit * microprocessor functionality. * * @author Ross Drew */ public class CPU { private final Memory memory; private final Registers registers = new Registers(); public static final int CARRY_INDICATOR_BIT = 0x100; //The bit set on a word when a byte has carried up public static final int NEGATIVE_INDICATOR_BIT = 0x80; //The bit set on a byte when a it is negative public CPU(Memory memory) { this.memory = memory; } /** * IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it- */ public void reset(){ System.out.println("*** RESETTING >>>"); registers.setRegister(Registers.REG_ACCUMULATOR, 0x0); registers.setRegister(Registers.REG_X_INDEX, 0x0); registers.setRegister(Registers.REG_Y_INDEX, 0x0); registers.setRegister(Registers.REG_STATUS, 0x34); registers.setRegister(Registers.REG_PC_HIGH, memory.getByte(0xFFFC)); registers.setRegister(Registers.REG_PC_LOW, memory.getByte(0xFFFD)); registers.setRegister(Registers.REG_SP, 0xFF); System.out.println("...READY!"); } /** * Get the value of the 16 bit Program Counter (PC) and increment */ private int getAndStepPC(){ final int originalPC = registers.getPC(); registers.setPC(originalPC + 1); return originalPC; } private int getByteOfMemoryAt(int location, int index){ final int memoryByte = memory.getByte(location + index); System.out.println("FETCH mem[" + location + (index != 0 ? "[" + index + "]" : "") +"] --> " + memoryByte); return memoryByte; } private int setByteOfMemoryAt(int location, int index, int newByte){ memory.setByteAt(location + index, newByte); System.out.println("STORE " + newByte + " --> mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]"); return (location + index); } private int getByteOfMemoryXIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX)); } private int setByteOfMemoryXIndexedAt(int location, int newByte){ return setByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX), newByte); } private int getByteOfMemoryYIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_Y_INDEX)); } private int getByteOfMemoryAt(int location){ return getByteOfMemoryAt(location, 0); } public Registers getRegisters(){ return registers; } /** * Return the next byte from program memory, as defined * by the Program Counter. * <em>Increments the Program Counter by 1</em> * * @return byte from PC[0] */ private int nextProgramByte(){ int memoryLocation = getAndStepPC(); return getByteOfMemoryAt(memoryLocation); } /** * Combine the next two bytes in program memory, as defined by * the Program Counter into a word so that:- * * PC[0] = high order byte * PC[1] = low order byte * * <em>Increments the Program Counter by 1</em> * * @return word made up of both bytes */ private int nextProgramWord(){ int byte1 = nextProgramByte(); return (byte1 << 8) | nextProgramByte() ; } public void step(int steps){ for (int i=0; i<steps; i++) step(); } public void step() { System.out.println("\n*** STEP >>>"); int accumulatorBeforeOperation = registers.getRegister(Registers.REG_ACCUMULATOR); int opCode = nextProgramByte(); //Execute the opcode System.out.println("Instruction: " + InstructionSet.getOpCodeName(opCode) + "..."); switch (opCode){ case InstructionSet.OP_ASL_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR) << 1; setCarryFlagBasedOn(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte); } break; case InstructionSet.OP_ASL_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_Z_IX: { int location = nextProgramByte(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS_IX: { int location = nextProgramWord(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS: { int location = nextProgramWord(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_LSR_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR); setBorrowFlagFor(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte >> 1); } break; case InstructionSet.OP_LSR_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location); setBorrowFlagFor(newFakeByte); newFakeByte = newFakeByte >> 1; registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ROL_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROL(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_ROL_Z: int location = nextProgramByte(); memory.setByteAt(location, performROL(memory.getByte(location))); break; /* Not implemented and/or not published on older 6502s */ case InstructionSet.OP_ROR_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROR(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_SEC: registers.setFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLC: registers.clearFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLV: registers.clearFlag(Registers.STATUS_FLAG_OVERFLOW); break; case InstructionSet.OP_INC_Z: { int incrementLocation = nextProgramByte(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_INC_ABS: { int incrementLocation = nextProgramWord(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_DEC_Z: { int decrementLocation = nextProgramByte(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_DEC_ABS: { int decrementLocation = nextProgramWord(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_INX: registers.incrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_DEX: registers.decrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_INY: registers.incrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_DEY: registers.decrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_LDX_I: registers.setRegisterAndFlags(Registers.REG_X_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDY_I: registers.setRegisterAndFlags(Registers.REG_Y_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDA_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_LDA_IY: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte()); break; case InstructionSet.OP_LDA_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_LDA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_Z: performAND(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS: performAND(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_AND_I: performAND(nextProgramByte()); break; case InstructionSet.OP_AND_Z_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_BIT_Z: int memData = memory.getByte(nextProgramByte()); if ((memData & registers.getRegister(Registers.REG_ACCUMULATOR)) == memData) registers.setFlag(Registers.STATUS_FLAG_ZERO); else registers.clearFlag(Registers.STATUS_FLAG_ZERO); //Set N, V to bits 7 and 6 of memory data registers.setRegister(Registers.REG_STATUS, (memData & 0b11000000) | (registers.getRegister(Registers.REG_STATUS) & 0b00111111)); break; case InstructionSet.OP_ORA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() | accumulatorBeforeOperation); break; case InstructionSet.OP_ORA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) | accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() ^ accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) ^ accumulatorBeforeOperation); break; case InstructionSet.OP_ADC_Z: performADC(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_ADC_I: performADC(nextProgramByte()); break; case InstructionSet.OP_ADC_ABS: performADC(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_ADC_Z_IX: performADC(getByteOfMemoryXIndexedAt(nextProgramByte())); break; //XXX Need to use 2s compliment addition (subtraction) // ? Do I deal with borrow in? does it need to manually set?! case InstructionSet.OP_CMP_I: int value = nextProgramByte(); int result = registers.getRegister(Registers.REG_ACCUMULATOR) - value; registers.setFlagsBasedOn(result & 0xFF); registers.setRegister(Registers.REG_ACCUMULATOR, result); break; case InstructionSet.OP_SBC_I: performSBC(nextProgramByte()); break; case InstructionSet.OP_SBC_Z: performSBC(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_STY_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_STA_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS: memory.setByteAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS_IX: setByteOfMemoryXIndexedAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STX_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_PHA: push(registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_PLA: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, pop()); break; case InstructionSet.OP_JMP_ABS: int h = nextProgramByte(); int l = nextProgramByte(); registers.setRegister(Registers.REG_PC_HIGH, h); registers.setRegister(Registers.REG_PC_LOW, l); break; case InstructionSet.OP_BCS: branchIf(registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BCC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BEQ: branchIf(registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BNE: branchIf(!registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BMI: branchIf(registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BPL: branchIf(!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BVS: branchIf(registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_BVC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_TAX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TAY: registers.setRegister(Registers.REG_Y_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TYA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_TXA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TXS: registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TSX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_SP)); registers.setFlagsBasedOn(registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_NOP: //Do nothing break; default: throw new UnknownOpCodeException("Unknown 6502 OpCode:" + opCode + " encountered.", opCode); } } private int pop(){ registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) + 1); int address = 0x0100 | registers.getRegister(Registers.REG_SP); return getByteOfMemoryAt(address); } private void push(int value){ memory.setByteAt(0x0100 | registers.getRegister(Registers.REG_SP), value); registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) - 1); } private int performROL(int initialValue){ int rotatedValue = (initialValue << 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); registers.setFlagsBasedOn(rotatedValue); setCarryFlagBasedOn(rotatedValue); return rotatedValue & 0xFF; } private int performROR(int initialValue){ int rotatedValue = (initialValue >> 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0b10000000 : 0); setBorrowFlagFor(initialValue); registers.setFlagsBasedOn(rotatedValue); return rotatedValue & 0xFF; } private void setBorrowFlagFor(int newFakeByte) { if ((newFakeByte & 0x1) == 0x1) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void setCarryFlagBasedOn(int newFakeByte) { if ((newFakeByte & CARRY_INDICATOR_BIT) == CARRY_INDICATOR_BIT) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void branchIf(boolean condition){ int location = nextProgramByte(); if (condition) branchTo(location); } /** * Branch to a relative location as defined by a signed byte * * @param displacement relative (-127 -> 128) location from end of branch instruction */ private void branchTo(int displacement) { int displacementByte = displacement & 0xFF; if ((displacementByte & NEGATIVE_INDICATOR_BIT) == NEGATIVE_INDICATOR_BIT) registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) - fromTwosComplimented(displacementByte)); else registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) + displacementByte); } private void performAND(int byteTerm){ registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, byteTerm & registers.getRegister(Registers.REG_ACCUMULATOR)); } private void performADC(int byteTerm){ int carry = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); addToAccumulator(byteTerm + carry); } //(1) compliment of carry flag added (so subtracted) as well //(2) set carry if no borrow required (A >= M[v]) private void performSBC(int byteTerm){ registers.setFlag(Registers.STATUS_FLAG_NEGATIVE); int borrow = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0 : 1); addToAccumulator(twosComplimentOf(byteTerm + borrow)); } private int twosComplimentOf(int byteValue){ return ((~byteValue) + 1) & 0xFF; } private int fromTwosComplimented(int byteValue){ return ((~byteValue)) & 0xFF; } /** * Perform a binary addition, setting Carry and Overflow flags as required. * * @param term term to add to the accumulator */ private void addToAccumulator(int term){ int result = registers.getRegister(Registers.REG_ACCUMULATOR) + term; //Set Carry, if bit 8 is set on new accumulator value, ignoring in 2s compliment addition (subtraction) if (!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)){ setCarryFlagBasedOn(result); }else { registers.clearFlag(Registers.STATUS_FLAG_CARRY); } //Set Overflow if the sign of both inputs is different from the sign of the result if (((registers.getRegister(Registers.REG_ACCUMULATOR) ^ result) & (term ^ result) & 0x80) != 0) registers.setFlag(Registers.STATUS_FLAG_OVERFLOW); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, result & 0xFF); } }
Refactor out addition to make it more flexable
src/main/java/com/rox/emu/p6502/CPU.java
Refactor out addition to make it more flexable
<ide><path>rc/main/java/com/rox/emu/p6502/CPU.java <ide> break; <ide> <ide> case InstructionSet.OP_ADC_Z: <del> performADC(getByteOfMemoryAt(nextProgramByte())); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramByte()))); <ide> break; <ide> <ide> case InstructionSet.OP_ADC_I: <del> performADC(nextProgramByte()); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(nextProgramByte())); <ide> break; <ide> <ide> case InstructionSet.OP_ADC_ABS: <del> performADC(getByteOfMemoryAt(nextProgramWord())); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramWord()))); <ide> break; <ide> <ide> case InstructionSet.OP_ADC_Z_IX: <del> performADC(getByteOfMemoryXIndexedAt(nextProgramByte())); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryXIndexedAt(nextProgramByte()))); <ide> break; <ide> <ide> //XXX Need to use 2s compliment addition (subtraction) <ide> break; <ide> <ide> case InstructionSet.OP_SBC_I: <del> performSBC(nextProgramByte()); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(nextProgramByte())); <ide> break; <ide> <ide> case InstructionSet.OP_SBC_Z: <del> performSBC(getByteOfMemoryAt(nextProgramByte())); <add> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(getByteOfMemoryAt(nextProgramByte()))); <ide> break; <ide> <ide> case InstructionSet.OP_STY_Z: <ide> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, byteTerm & registers.getRegister(Registers.REG_ACCUMULATOR)); <ide> } <ide> <del> private void performADC(int byteTerm){ <add> private int performADC(int byteTerm){ <ide> int carry = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); <del> addToAccumulator(byteTerm + carry); <add> return addToAccumulator(byteTerm + carry); <ide> } <ide> <ide> //(1) compliment of carry flag added (so subtracted) as well <ide> //(2) set carry if no borrow required (A >= M[v]) <del> private void performSBC(int byteTerm){ <add> private int performSBC(int byteTerm){ <ide> registers.setFlag(Registers.STATUS_FLAG_NEGATIVE); <ide> int borrow = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0 : 1); <del> addToAccumulator(twosComplimentOf(byteTerm + borrow)); <add> return addToAccumulator(twosComplimentOf(byteTerm + borrow)); <ide> } <ide> <ide> private int twosComplimentOf(int byteValue){ <ide> * <ide> * @param term term to add to the accumulator <ide> */ <del> private void addToAccumulator(int term){ <add> private int addToAccumulator(int term){ <ide> int result = registers.getRegister(Registers.REG_ACCUMULATOR) + term; <ide> <ide> //Set Carry, if bit 8 is set on new accumulator value, ignoring in 2s compliment addition (subtraction) <ide> if (((registers.getRegister(Registers.REG_ACCUMULATOR) ^ result) & (term ^ result) & 0x80) != 0) <ide> registers.setFlag(Registers.STATUS_FLAG_OVERFLOW); <ide> <del> registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, result & 0xFF); <add> return (result & 0xFF); <ide> } <ide> }
Java
apache-2.0
a9de4b818e909055cd56d9fee99ba5ab87ae1c4b
0
nla/tinycdxserver,nla/outbackcdx,nla/tinycdxserver,nla/outbackcdx,nla/tinycdxserver,nla/outbackcdx,nla/tinycdxserver,nla/outbackcdx
package outbackcdx; import java.util.HashMap; import java.util.Map; /** * Experimental features that can be turned on with a flag. This is so they can * be merged into master (thus avoiding the code diverging) before they are * mature. */ public class FeatureFlags { private static boolean experimentalAccessControl; private static boolean pandoraHacks; private static boolean secondaryMode; private static boolean acceptWrites; static { experimentalAccessControl = "1".equals(System.getenv("EXPERIMENTAL_ACCESS_CONTROL")); pandoraHacks = "1".equals(System.getenv("PANDORA_HACKS")); } public static boolean pandoraHacks() { return pandoraHacks; } public static boolean experimentalAccessControl() { return experimentalAccessControl; } public static void setExperimentalAccessControl(boolean enabled) { experimentalAccessControl = enabled; } public static void setSecondaryMode(boolean enabled){ secondaryMode = enabled; } public static boolean isSecondary() { return secondaryMode; } public static void setAcceptWrites(boolean enabled){ acceptWrites = enabled; } public static boolean acceptsWrites() { return acceptWrites; } public static Map<String, Boolean> asMap() { Map<String,Boolean> map = new HashMap<>(); map.put("experimentalAccessControl", experimentalAccessControl()); map.put("pandoraHacks", pandoraHacks()); map.put("secondaryMode", isSecondary()); map.put("acceptsWrites", acceptsWrites()); return map; } public static void setPandoraHacks(boolean pandoraHacks) { FeatureFlags.pandoraHacks = pandoraHacks; } }
src/outbackcdx/FeatureFlags.java
package outbackcdx; import java.util.HashMap; import java.util.Map; /** * Experimental features that can be turned on with a flag. This is so they can * be merged into master (thus avoiding the code diverging) before they are * mature. */ public class FeatureFlags { private static boolean experimentalAccessControl; private static boolean pandoraHacks; private static boolean secondaryMode; static { experimentalAccessControl = "1".equals(System.getenv("EXPERIMENTAL_ACCESS_CONTROL")); pandoraHacks = "1".equals(System.getenv("PANDORA_HACKS")); } public static boolean pandoraHacks() { return pandoraHacks; } public static boolean experimentalAccessControl() { return experimentalAccessControl; } public static void setExperimentalAccessControl(boolean enabled) { experimentalAccessControl = enabled; } public static void setSecondaryMode(boolean enabled){ secondaryMode = enabled; } public static boolean isSecondary() { return secondaryMode; } public static void setAcceptWrites(boolean enabled){ acceptWrites = enabled; } public static boolean acceptsWrites() { return acceptWrites; } public static Map<String, Boolean> asMap() { Map<String,Boolean> map = new HashMap<>(); map.put("experimentalAccessControl", experimentalAccessControl()); map.put("pandoraHacks", pandoraHacks()); map.put("secondaryMode", isSecondary()); map.put("acceptsWrites", acceptsWrites()); return map; } public static void setPandoraHacks(boolean pandoraHacks) { FeatureFlags.pandoraHacks = pandoraHacks; } }
forgot to expressly add the variable
src/outbackcdx/FeatureFlags.java
forgot to expressly add the variable
<ide><path>rc/outbackcdx/FeatureFlags.java <ide> private static boolean experimentalAccessControl; <ide> private static boolean pandoraHacks; <ide> private static boolean secondaryMode; <add> private static boolean acceptWrites; <ide> <ide> static { <ide> experimentalAccessControl = "1".equals(System.getenv("EXPERIMENTAL_ACCESS_CONTROL"));
Java
apache-2.0
9b2362e8e4c523f470c9d8f07a62fb36c7cc561b
0
pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript
package org.bds.run; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.bds.Bds; import org.bds.BdsParseArgs; import org.bds.Config; import org.bds.compile.BdsCompiler; import org.bds.compile.CompilerMessages; import org.bds.executioner.Executioner; import org.bds.executioner.Executioners; import org.bds.executioner.Executioners.ExecutionerType; import org.bds.lang.BdsNodeFactory; import org.bds.lang.ProgramUnit; import org.bds.lang.nativeFunctions.NativeLibraryFunctions; import org.bds.lang.nativeMethods.string.NativeLibraryString; import org.bds.lang.statement.FunctionDeclaration; import org.bds.lang.statement.Statement; import org.bds.lang.statement.VarDeclaration; import org.bds.lang.type.Types; import org.bds.scope.GlobalScope; import org.bds.symbol.GlobalSymbolTable; import org.bds.task.TaskDependecies; import org.bds.util.Timer; /** * Run a bds program * * @author pcingola */ public class BdsRun { public static boolean USE_VM = true; // Use VM public enum BdsAction { RUN, RUN_CHECKPOINT, ASSEMBLY, COMPILE, INFO_CHECKPOINT, TEST, CHECK_PID_REGEX } boolean debug; // debug mode boolean log; // Log everything (keep STDOUT, SDTERR and ExitCode files) boolean stackCheck; // Check stack size when thread finishes runnig (should be zero) boolean verbose; // Verbose mode int exitValue; String chekcpointRestoreFile; // Restore file String programFileName; // Program file name Config config; BdsAction bdsAction; BdsThread bdsThread; ProgramUnit programUnit; // Program (parsed nodes) List<String> programArgs; // Command line arguments for BigDataScript program public BdsRun() { bdsAction = BdsAction.RUN; programArgs = new ArrayList<>(); } public void addArg(String arg) { programArgs.add(arg); } /** * Print assembly code to STDOUT */ int assembly() { // Compile, abort on errors if (!compile()) return 1; try { System.out.println(programUnit.toAsm()); } catch (Throwable t) { if (verbose) t.printStackTrace(); return 1; } return 0; } /** * Check 'pidRegex' */ public void checkPidRegex() { // PID regex matcher String pidPatternStr = config.getPidRegex(""); if (pidPatternStr.isEmpty()) { System.err.println("Cannot find 'pidRegex' entry in config file."); System.exit(1); } Executioner executioner = Executioners.getInstance().get(ExecutionerType.CLUSTER); // Show pattern System.out.println("Matching pidRegex '" + pidPatternStr + "'"); // Read STDIN and check pattern try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String pid = executioner.parsePidLine(line); System.out.println("Input line:\t'" + line + "'\tMatched: '" + pid + "'"); } } catch (IOException e) { e.printStackTrace(); } executioner.kill(); // Kill executioner } /** * Compile program * @return True if compiled OK */ public boolean compile() { if (debug) Timer.showStdErr("Parsing"); BdsCompiler compiler = new BdsCompiler(programFileName); programUnit = compiler.compile(); // Show errors and warnings, if any if ((programUnit == null) && !CompilerMessages.get().isEmpty()) { System.err.println("Compiler messages:\n" + CompilerMessages.get()); } return programUnit != null; } public BdsAction getBdsAction() { return bdsAction; } public BdsThread getBdsThread() { return bdsThread; } public List<String> getProgramArgs() { return programArgs; } public ProgramUnit getProgramUnit() { return programUnit; } /** * Show information from a checkpoint file */ int infoCheckpoint() { // Load checkpoint file // TODO: LOAD FROM CHECKLPOINT !!!!!!!!!!!!! // for (BdsThread bdsThread : bdsThreads) // bdsThread.print(); return 0; } /** * Initialize before running or type-checking */ void initialize() { Types.reset(); // Reset node factory BdsNodeFactory.reset(); // Startup message if (log || debug) Timer.showStdErr(Bds.VERSION); // Global scope GlobalSymbolTable.reset(); GlobalScope.reset(); GlobalScope.get().initilaize(config); // Libraries initilaizeLibraries(); } /** * Initialize standard libraries */ void initilaizeLibraries() { if (debug) log("Initialize standard libraries."); // Native functions NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions(); if (debug) log("Native library:\n" + nativeLibraryFunctions); // Native library: String NativeLibraryString nativeLibraryString = new NativeLibraryString(); if (debug) log("Native library:\n" + nativeLibraryString); } void log(String msg) { Timer.showStdErr(getClass().getSimpleName() + ": " + msg); } /** * Run program */ public int run() { // Initialize initialize(); Executioners executioners = Executioners.getInstance(config); TaskDependecies.reset(); //--- // Run //--- switch (bdsAction) { case ASSEMBLY: exitValue = assembly(); break; case COMPILE: exitValue = compile() ? 0 : 1; break; case RUN_CHECKPOINT: exitValue = runCheckpoint(); break; case INFO_CHECKPOINT: exitValue = infoCheckpoint(); break; case TEST: exitValue = runTests(); break; case CHECK_PID_REGEX: checkPidRegex(); exitValue = 0; break; default: exitValue = runCompile(); // BdsCompiler & run } if (debug) Timer.showStdErr("Finished. Exit code: " + exitValue); //--- // Kill all executioners //--- for (Executioner executioner : executioners.getAll()) executioner.kill(); config.kill(); // Kill 'tail' and 'monitor' threads return exitValue; } /** * Restore from checkpoint and run */ int runCheckpoint() { // Load checkpoint file // TODO: REMOVE BdsSerializer // BdsSerializer bdsSerializer = new BdsSerializer(chekcpointRestoreFile, config); // List<BdsThread> bdsThreads = bdsSerializer.load(); BdsThread bdsThreadRoot; try { ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(chekcpointRestoreFile))); bdsThreadRoot = (BdsThread) in.readObject(); in.close(); } catch (Exception e) { throw new RuntimeException("Error while serializing to file '" + chekcpointRestoreFile + "'", e); } // Set main thread's programUnit running scope (mostly for debugging and test cases) // ProgramUnit's scope it the one before 'global' // BdsThread mainThread = bdsThreads.get(0); BdsThread mainThread = bdsThreadRoot; programUnit = mainThread.getProgramUnit(); // Set state and recover tasks List<BdsThread> bdsThreads = bdsThreadRoot.getBdsThreads(); bdsThreads.add(bdsThreadRoot); for (BdsThread bdsThread : bdsThreads) { if (bdsThread.isFinished()) { // Thread finished before serialization: Nothing to do } else { bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks } } // All set, run main thread return runThread(mainThread); } /** * BdsCompiler and run */ int runCompile() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Show script's automatic help message if (bdsParseArgs.isShowHelp()) { if (debug) Timer.showStdErr("Showing automaic 'help'"); HelpCreator hc = new HelpCreator(programUnit); System.out.println(hc); return 0; } // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) { Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); Timer.showStdErr("Running"); } int exitCode = runThread(bdsThread); // Check stack if (stackCheck) bdsThread.sanityCheckStack(); return exitCode; } /** * BdsCompiler and run */ int runTests() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (debug) Timer.showStdErr("Running tests"); ProgramUnit pu = bdsThread.getProgramUnit(); return runTests(pu); } /** * For each "test*()" function in ProgramUnit, create a thread * that executes the function's body */ int runTests(ProgramUnit progUnit) { // We need to execute all variable declarations in order to be able to use global vairables in 'test*()' functions" List<VarDeclaration> varDecls = programUnit.varDeclarations(false); List<FunctionDeclaration> testFuncs = progUnit.testsFunctions(); int exitCode = 0; int testOk = 0, testError = 0; for (FunctionDeclaration testFunc : testFuncs) { System.out.println(""); // Run each function int exitValTest = runTests(progUnit, testFunc, varDecls); // Show test result if (exitValTest == 0) { Timer.show("Test '" + testFunc.getFunctionName() + "': OK"); testOk++; } else { Timer.show("Test '" + testFunc.getFunctionName() + "': FAIL"); exitCode = 1; testError++; } } // Show results System.out.println(""); Timer.show("Totals"// + "\n OK : " + testOk // + "\n ERROR : " + testError // ); return exitCode; } /** * Run a single test function, return exit code */ int runTests(ProgramUnit progUnit, FunctionDeclaration testFunc, List<VarDeclaration> varDecls) { List<Statement> statements = new ArrayList<>(); // Add all variable declarations for (VarDeclaration varDecl : varDecls) statements.add(varDecl); // Note: We execute the function's body (not the function declaration) statements.add(testFunc.getStatement()); // Create a program unit having all variable declarations and the test function's statements ProgramUnit puTest = new ProgramUnit(progUnit, null); puTest.setStatements(statements.toArray(new Statement[0])); BdsThread bdsTestThread = new BdsThread(puTest, config); int exitValTest = runThread(bdsTestThread); return exitValTest; } /** * Run a thread */ int runThread(BdsThread bdsThread) { this.bdsThread = bdsThread; if (bdsThread.isFinished()) return 0; bdsThread.start(); try { bdsThread.join(); } catch (InterruptedException e) { // Nothing to do? // May be checkpoint? return 1; } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); // OK, we are done return bdsThread.getExitValue(); } public void setBdsAction(BdsAction bdsAction) { this.bdsAction = bdsAction; } public void setChekcpointRestoreFile(String chekcpointRestoreFile) { this.chekcpointRestoreFile = chekcpointRestoreFile; } public void setConfig(Config config) { this.config = config; } public void setDebug(boolean debug) { this.debug = debug; } public void setLog(boolean log) { this.log = log; } public void setProgramArgs(ArrayList<String> programArgs) { this.programArgs = programArgs; } public void setProgramFileName(String programFileName) { this.programFileName = programFileName; } public void setProgramUnit(ProgramUnit programUnit) { this.programUnit = programUnit; } public void setStackCheck(boolean stackCheck) { this.stackCheck = stackCheck; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
src/org/bds/run/BdsRun.java
package org.bds.run; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.bds.Bds; import org.bds.BdsParseArgs; import org.bds.Config; import org.bds.compile.BdsCompiler; import org.bds.compile.CompilerMessages; import org.bds.executioner.Executioner; import org.bds.executioner.Executioners; import org.bds.executioner.Executioners.ExecutionerType; import org.bds.lang.BdsNodeFactory; import org.bds.lang.ProgramUnit; import org.bds.lang.nativeFunctions.NativeLibraryFunctions; import org.bds.lang.nativeMethods.string.NativeLibraryString; import org.bds.lang.statement.FunctionDeclaration; import org.bds.lang.statement.Statement; import org.bds.lang.statement.VarDeclaration; import org.bds.lang.type.Types; import org.bds.scope.GlobalScope; import org.bds.symbol.GlobalSymbolTable; import org.bds.task.TaskDependecies; import org.bds.util.Timer; /** * Run a bds program * * @author pcingola */ public class BdsRun { public enum BdsAction { RUN, RUN_CHECKPOINT, ASSEMBLY, COMPILE, INFO_CHECKPOINT, TEST, CHECK_PID_REGEX } boolean debug; // debug mode boolean log; // Log everything (keep STDOUT, SDTERR and ExitCode files) boolean stackCheck; // Check stack size when thread finishes runnig (should be zero) boolean verbose; // Verbose mode int exitValue; String chekcpointRestoreFile; // Restore file String programFileName; // Program file name Config config; BdsAction bdsAction; BdsThread bdsThread; ProgramUnit programUnit; // Program (parsed nodes) List<String> programArgs; // Command line arguments for BigDataScript program public BdsRun() { bdsAction = BdsAction.RUN; programArgs = new ArrayList<>(); } public void addArg(String arg) { programArgs.add(arg); } /** * Print assembly code to STDOUT */ int assembly() { // Compile, abort on errors if (!compile()) return 1; try { System.out.println(programUnit.toAsm()); } catch (Throwable t) { if (verbose) t.printStackTrace(); return 1; } return 0; } /** * Check 'pidRegex' */ public void checkPidRegex() { // PID regex matcher String pidPatternStr = config.getPidRegex(""); if (pidPatternStr.isEmpty()) { System.err.println("Cannot find 'pidRegex' entry in config file."); System.exit(1); } Executioner executioner = Executioners.getInstance().get(ExecutionerType.CLUSTER); // Show pattern System.out.println("Matching pidRegex '" + pidPatternStr + "'"); // Read STDIN and check pattern try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String pid = executioner.parsePidLine(line); System.out.println("Input line:\t'" + line + "'\tMatched: '" + pid + "'"); } } catch (IOException e) { e.printStackTrace(); } executioner.kill(); // Kill executioner } /** * Compile program * @return True if compiled OK */ public boolean compile() { if (debug) Timer.showStdErr("Parsing"); BdsCompiler compiler = new BdsCompiler(programFileName); programUnit = compiler.compile(); // Show errors and warnings, if any if ((programUnit == null) && !CompilerMessages.get().isEmpty()) { System.err.println("Compiler messages:\n" + CompilerMessages.get()); } return programUnit != null; } public BdsAction getBdsAction() { return bdsAction; } public BdsThread getBdsThread() { return bdsThread; } public List<String> getProgramArgs() { return programArgs; } public ProgramUnit getProgramUnit() { return programUnit; } /** * Show information from a checkpoint file */ int infoCheckpoint() { // Load checkpoint file // TODO: LOAD FROM CHECKLPOINT !!!!!!!!!!!!! // for (BdsThread bdsThread : bdsThreads) // bdsThread.print(); return 0; } /** * Initialize before running or type-checking */ void initialize() { Types.reset(); // Reset node factory BdsNodeFactory.reset(); // Startup message if (log || debug) Timer.showStdErr(Bds.VERSION); // Global scope GlobalSymbolTable.reset(); GlobalScope.reset(); GlobalScope.get().initilaize(config); // Libraries initilaizeLibraries(); } /** * Initialize standard libraries */ void initilaizeLibraries() { if (debug) log("Initialize standard libraries."); // Native functions NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions(); if (debug) log("Native library:\n" + nativeLibraryFunctions); // Native library: String NativeLibraryString nativeLibraryString = new NativeLibraryString(); if (debug) log("Native library:\n" + nativeLibraryString); } void log(String msg) { Timer.showStdErr(getClass().getSimpleName() + ": " + msg); } /** * Run program */ public int run() { // Initialize initialize(); Executioners executioners = Executioners.getInstance(config); TaskDependecies.reset(); //--- // Run //--- switch (bdsAction) { case ASSEMBLY: exitValue = assembly(); break; case COMPILE: exitValue = compile() ? 0 : 1; break; case RUN_CHECKPOINT: exitValue = runCheckpoint(); break; case INFO_CHECKPOINT: exitValue = infoCheckpoint(); break; case TEST: exitValue = runTests(); break; case CHECK_PID_REGEX: checkPidRegex(); exitValue = 0; break; default: exitValue = runCompile(); // BdsCompiler & run } if (debug) Timer.showStdErr("Finished. Exit code: " + exitValue); //--- // Kill all executioners //--- for (Executioner executioner : executioners.getAll()) executioner.kill(); config.kill(); // Kill 'tail' and 'monitor' threads return exitValue; } /** * Restore from checkpoint and run */ int runCheckpoint() { // Load checkpoint file // TODO: REMOVE BdsSerializer // BdsSerializer bdsSerializer = new BdsSerializer(chekcpointRestoreFile, config); // List<BdsThread> bdsThreads = bdsSerializer.load(); BdsThread bdsThreadRoot; try { ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(chekcpointRestoreFile))); bdsThreadRoot = (BdsThread) in.readObject(); in.close(); } catch (Exception e) { throw new RuntimeException("Error while serializing to file '" + chekcpointRestoreFile + "'", e); } // Set main thread's programUnit running scope (mostly for debugging and test cases) // ProgramUnit's scope it the one before 'global' // BdsThread mainThread = bdsThreads.get(0); BdsThread mainThread = bdsThreadRoot; programUnit = mainThread.getProgramUnit(); // Set state and recover tasks List<BdsThread> bdsThreads = bdsThreadRoot.getBdsThreads(); bdsThreads.add(bdsThreadRoot); for (BdsThread bdsThread : bdsThreads) { if (bdsThread.isFinished()) { // Thread finished before serialization: Nothing to do } else { bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks } } // All set, run main thread return runThread(mainThread); } /** * BdsCompiler and run */ int runCompile() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Show script's automatic help message if (bdsParseArgs.isShowHelp()) { if (debug) Timer.showStdErr("Showing automaic 'help'"); HelpCreator hc = new HelpCreator(programUnit); System.out.println(hc); return 0; } // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) { Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); Timer.showStdErr("Running"); } int exitCode = runThread(bdsThread); // Check stack if (stackCheck) bdsThread.sanityCheckStack(); return exitCode; } /** * BdsCompiler and run */ int runTests() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (debug) Timer.showStdErr("Running tests"); ProgramUnit pu = bdsThread.getProgramUnit(); return runTests(pu); } /** * For each "test*()" function in ProgramUnit, create a thread * that executes the function's body */ int runTests(ProgramUnit progUnit) { // We need to execute all variable declarations in order to be able to use global vairables in 'test*()' functions" List<VarDeclaration> varDecls = programUnit.varDeclarations(false); List<FunctionDeclaration> testFuncs = progUnit.testsFunctions(); int exitCode = 0; int testOk = 0, testError = 0; for (FunctionDeclaration testFunc : testFuncs) { System.out.println(""); // Run each function int exitValTest = runTests(progUnit, testFunc, varDecls); // Show test result if (exitValTest == 0) { Timer.show("Test '" + testFunc.getFunctionName() + "': OK"); testOk++; } else { Timer.show("Test '" + testFunc.getFunctionName() + "': FAIL"); exitCode = 1; testError++; } } // Show results System.out.println(""); Timer.show("Totals"// + "\n OK : " + testOk // + "\n ERROR : " + testError // ); return exitCode; } /** * Run a single test function, return exit code */ int runTests(ProgramUnit progUnit, FunctionDeclaration testFunc, List<VarDeclaration> varDecls) { List<Statement> statements = new ArrayList<>(); // Add all variable declarations for (VarDeclaration varDecl : varDecls) statements.add(varDecl); // Note: We execute the function's body (not the function declaration) statements.add(testFunc.getStatement()); // Create a program unit having all variable declarations and the test function's statements ProgramUnit puTest = new ProgramUnit(progUnit, null); puTest.setStatements(statements.toArray(new Statement[0])); BdsThread bdsTestThread = new BdsThread(puTest, config); int exitValTest = runThread(bdsTestThread); return exitValTest; } /** * Run a thread */ int runThread(BdsThread bdsThread) { this.bdsThread = bdsThread; if (bdsThread.isFinished()) return 0; bdsThread.start(); try { bdsThread.join(); } catch (InterruptedException e) { // Nothing to do? // May be checkpoint? return 1; } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); // OK, we are done return bdsThread.getExitValue(); } public void setBdsAction(BdsAction bdsAction) { this.bdsAction = bdsAction; } public void setChekcpointRestoreFile(String chekcpointRestoreFile) { this.chekcpointRestoreFile = chekcpointRestoreFile; } public void setConfig(Config config) { this.config = config; } public void setDebug(boolean debug) { this.debug = debug; } public void setLog(boolean log) { this.log = log; } public void setProgramArgs(ArrayList<String> programArgs) { this.programArgs = programArgs; } public void setProgramFileName(String programFileName) { this.programFileName = programFileName; } public void setProgramUnit(ProgramUnit programUnit) { this.programUnit = programUnit; } public void setStackCheck(boolean stackCheck) { this.stackCheck = stackCheck; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
Project updated
src/org/bds/run/BdsRun.java
Project updated
<ide><path>rc/org/bds/run/BdsRun.java <ide> */ <ide> public class BdsRun { <ide> <add> public static boolean USE_VM = true; // Use VM <add> <ide> public enum BdsAction { <ide> RUN, RUN_CHECKPOINT, ASSEMBLY, COMPILE, INFO_CHECKPOINT, TEST, CHECK_PID_REGEX <ide> }
Java
mit
error: pathspec 'Javelin/src/main/java/jp/co/acroquest/endosnipe/javelin/jdbc/stats/LightweightJdbcJavelinRecorder.java' did not match any file(s) known to git
c055a7191103e056240b092f377a5773eff7356e
1
miyasakago/ENdoSnipe,t-hiramatsu/ENdoSnipe,t-hiramatsu/ENdoSnipe,miyasakago/ENdoSnipe,ryokato/ENdoSnipe,ryokato/ENdoSnipe,miyasakago/ENdoSnipe,ryokato/ENdoSnipe,t-hiramatsu/ENdoSnipe,ryokato/ENdoSnipe,miyasakago/ENdoSnipe,ryokato/ENdoSnipe,t-hiramatsu/ENdoSnipe,miyasakago/ENdoSnipe,ryokato/ENdoSnipe,t-hiramatsu/ENdoSnipe,miyasakago/ENdoSnipe,t-hiramatsu/ENdoSnipe
/* * Copyright (c) 2004-2013 Acroquest Technology Co., Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technology Co., Ltd., WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package jp.co.acroquest.endosnipe.javelin.jdbc.stats; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Statement; import jp.co.acroquest.endosnipe.common.config.JavelinConfig; import jp.co.acroquest.endosnipe.common.event.EventConstants; import jp.co.acroquest.endosnipe.common.logger.SystemLogger; import jp.co.acroquest.endosnipe.javelin.CallTree; import jp.co.acroquest.endosnipe.javelin.CallTreeNode; import jp.co.acroquest.endosnipe.javelin.CallTreeRecorder; import jp.co.acroquest.endosnipe.javelin.RecordStrategy; import jp.co.acroquest.endosnipe.javelin.StatsJavelinRecorder; import jp.co.acroquest.endosnipe.javelin.jdbc.common.JdbcJavelinConfig; /** * JDBCJavelinLightweightモード詳細設計仕様書 * @author heinminn * */ public class LightweightJdbcJavelinRecorder { /** 設定値保持Bean */ private static JdbcJavelinConfig config__ = new JdbcJavelinConfig(); private static JavelinConfig logArgsConfig__ = new JavelinConfig() { public boolean isLogArgs() { return true; } }; /** * constructor of this class */ public LightweightJdbcJavelinRecorder() { //Do nothing } /** * JDBCJavelinのパラメータを設定する。 * @param config JDBCJavelinの設定 */ public static void setJdbcJavelinConfig(final JdbcJavelinConfig config) { LightweightJdbcJavelinRecorder.config__ = config; } /** * 設定を取得する。 * * @return 設定。 */ public static JdbcJavelinConfig getConfig() { return config__; } /** * * @param stmt Statement object */ public static void preProcess(Statement stmt) { JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); if (jdbcJvnStatus.getCallDepth() == 0) { jdbcJvnStatus.clearPreprocessedDepthSet(); } try { String jdbcUrl = "DB-Server"; Connection connection = stmt.getConnection(); JdbcJavelinConnection jvnConnection = null; if (connection != null) { jvnConnection = (JdbcJavelinConnection)connection; jdbcUrl = getJdbcUrl(connection, jvnConnection); } String className = jdbcUrl; Boolean noSql = Boolean.FALSE; jdbcJvnStatus.setNoSql(noSql); CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); CallTree callTree = callTreeRecorder.getCallTree(); execNoDuplicateCall(jdbcJvnStatus, callTreeRecorder, callTree); jdbcJvnStatus.savePreprocessDepth(); // StatsJavelinRecorderに処理を委譲する StatsJavelinRecorder.preProcess(className, "sql", null, logArgsConfig__, true); } catch (Exception ex) { // 想定外の例外が発生した場合は標準エラー出力に出力しておく。 SystemLogger.getInstance().warn(ex); } finally { jdbcJvnStatus.incrementCallDepth(); } } private static String getJdbcUrl(Connection connection, JdbcJavelinConnection jvnConnection) throws SQLException { String jdbcUrl; jdbcUrl = jvnConnection.getJdbcUrl(); if (jdbcUrl == null) { DatabaseMetaData metaData = connection.getMetaData(); if (metaData != null) { jdbcUrl = metaData.getURL(); jvnConnection.setJdbcUrl(jdbcUrl); } } return jdbcUrl; } private static void execNoDuplicateCall(JdbcJvnStatus jdbcJvnStatus, CallTreeRecorder callTreeRecorder, CallTree tree) { int depth = jdbcJvnStatus.incrementDepth(); if (depth > 1) { CallTreeNode node = callTreeRecorder.getCallTreeNode(); CallTreeNode parent = node.getParent(); if (parent != null) { callTreeRecorder.removeChildNode(parent, node); } else { // 親ノードがルートの場合は、ルートを null にする tree.setRootNode(null); } callTreeRecorder.setCallerNode(parent); } } /** * 後処理(本処理成功時)。 * */ public static void postProcessOK() { JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); try { jdbcJvnStatus.decrementCallDepth(); // 実行計画取得中であれば、前処理・後処理は行わない。 if (jdbcJvnStatus.getNowExpalaining() != null) { return; } try { boolean result = ignore(jdbcJvnStatus); if (result == true) { jdbcJvnStatus.removePreProcessDepth(); return; } } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } if (jdbcJvnStatus.isPreprocessDepth() == false) { return; } jdbcJvnStatus.removePreProcessDepth(); // SQLトレース取得中状態以外の場合は、実行計画は取得しない。 CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); CallTree tree = callTreeRecorder.getCallTree(); CallTreeNode node = null; if (tree == null || (config__.isAllowSqlTraceForOracle() // && (tree.containsFlag(SqlTraceStatus.KEY_SESSION_INITIALIZING) // || tree.containsFlag(SqlTraceStatus.KEY_SESSION_CLOSING) // || tree.containsFlag(SqlTraceStatus.KEY_SESSION_FINISHED)))) { return; } // 呼び出し元情報取得。 node = callTreeRecorder.getCallTreeNode(); // オリジナルのargsへの参照をローカル変数に一時保存 String[] oldArgs = node.getArgs(); if (oldArgs == null) { oldArgs = new String[0]; } // SQL呼び出し回数をrootのCallTreeNodeに保持する if (config__.isSqlcountMonitor()) { RecordStrategy rs = getRecordStrategy(tree, EventConstants.NAME_SQLCOUNT); if (rs != null && rs instanceof SqlCountStrategy && oldArgs.length > 0) { // SQLCountStrategyのSQL呼び出し回数を増加させる SqlCountStrategy strategy = (SqlCountStrategy)rs; strategy.incrementSQLCount(oldArgs[0]); } } } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } finally { StatsJavelinRecorder.postProcess(null, null, (Object)null, config__, true); jdbcJvnStatus.setExecPlanSql(null); } } private static boolean ignore(JdbcJvnStatus jdbcJvnStatus) { boolean result = false; if (Boolean.TRUE.equals(jdbcJvnStatus.isNoSql())) { Boolean noSql = Boolean.FALSE; jdbcJvnStatus.setNoSql(noSql); result = true; } else { // JDBC呼出し重複出力フラグがOFF、かつ最深ノードでなければ、 // 何もしない。 int depth = jdbcJvnStatus.getDepth(); if (config__.isRecordDuplJdbcCall() == false && depth > 0) { jdbcJvnStatus.decrementDepth(); if (depth < jdbcJvnStatus.getDepthMax()) { result = true; } } } return result; } private static RecordStrategy getRecordStrategy(CallTree callTree, String strategyKey) { RecordStrategy rs = callTree.getRecordStrategy(strategyKey); if (rs == null) { if (EventConstants.NAME_SQLCOUNT.equals(strategyKey)) { // SQLCountStrategyが登録されていない場合は、新規に登録する rs = new SqlCountStrategy(); callTree.addRecordStrategy(strategyKey, rs); } else if (SqlPlanStrategy.KEY.equals(strategyKey)) { // SQLPlanStrategyが登録されていない場合は、新規に登録する rs = new SqlPlanStrategy(); callTree.addRecordStrategy(strategyKey, rs); } } return rs; } /** * 後処理(本処理失敗時)。 * */ public static void postProcessNG(final Throwable cause) { try { JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); CallTree tree = callTreeRecorder.getCallTree(); if (tree.isJdbcEnabled() == false) { return; } jdbcJvnStatus.decrementCallDepth(); // 実行計画取得中であれば、前処理・後処理は行わない。 if (jdbcJvnStatus.getNowExpalaining() != null) { return; } // セッション終了処理に入っている場合は、実行計画は取得しない。 if ((config__.isAllowSqlTraceForOracle() // && (tree.containsFlag(SqlTraceStatus.KEY_SESSION_INITIALIZING) // || tree.containsFlag(SqlTraceStatus.KEY_SESSION_CLOSING) // || tree.containsFlag(SqlTraceStatus.KEY_SESSION_FINISHED)))) { return; } if (jdbcJvnStatus.isPreprocessDepth() == false) { return; } jdbcJvnStatus.removePreProcessDepth(); try { // 親ノードが"DB-Server"、かつJDBC呼出し重複出力フラグがOFFなら処理を終了。 if (ignore(jdbcJvnStatus)) { return; } } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } recordPostNG(cause, jdbcJvnStatus); } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } finally { StatsJavelinRecorder.postProcess(null, null, cause, config__, true); } } public static void recordPostNG(final Throwable cause, JdbcJvnStatus jdbcJvnStatus) { // JavelinRecorderに処理委譲 CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); CallTreeNode node = callTreeRecorder.getCallTreeNode(); if (node != null) { StatsJavelinRecorder.postProcess(null, null, cause, config__, true); jdbcJvnStatus.setExecPlanSql(null); } } }
Javelin/src/main/java/jp/co/acroquest/endosnipe/javelin/jdbc/stats/LightweightJdbcJavelinRecorder.java
Issue#172 JDBCJavelin Lightweight mode.
Javelin/src/main/java/jp/co/acroquest/endosnipe/javelin/jdbc/stats/LightweightJdbcJavelinRecorder.java
Issue#172 JDBCJavelin Lightweight mode.
<ide><path>avelin/src/main/java/jp/co/acroquest/endosnipe/javelin/jdbc/stats/LightweightJdbcJavelinRecorder.java <add>/* <add> * Copyright (c) 2004-2013 Acroquest Technology Co., Ltd. All Rights Reserved. <add> * Please read the associated COPYRIGHTS file for more details. <add> * <add> * THE SOFTWARE IS PROVIDED BY Acroquest Technology Co., Ltd., WITHOUT WARRANTY OF <add> * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE <add> * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE <add> * AND NONINFRINGEMENT. <add> * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDER BE LIABLE FOR ANY <add> * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING <add> * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. <add> */ <add>package jp.co.acroquest.endosnipe.javelin.jdbc.stats; <add> <add>import java.sql.Connection; <add>import java.sql.DatabaseMetaData; <add>import java.sql.SQLException; <add>import java.sql.Statement; <add> <add>import jp.co.acroquest.endosnipe.common.config.JavelinConfig; <add>import jp.co.acroquest.endosnipe.common.event.EventConstants; <add>import jp.co.acroquest.endosnipe.common.logger.SystemLogger; <add>import jp.co.acroquest.endosnipe.javelin.CallTree; <add>import jp.co.acroquest.endosnipe.javelin.CallTreeNode; <add>import jp.co.acroquest.endosnipe.javelin.CallTreeRecorder; <add>import jp.co.acroquest.endosnipe.javelin.RecordStrategy; <add>import jp.co.acroquest.endosnipe.javelin.StatsJavelinRecorder; <add>import jp.co.acroquest.endosnipe.javelin.jdbc.common.JdbcJavelinConfig; <add> <add>/** <add> * JDBCJavelinLightweightモード詳細設計仕様書 <add> * @author heinminn <add> * <add> */ <add>public class LightweightJdbcJavelinRecorder <add>{ <add> <add> /** 設定値保持Bean */ <add> private static JdbcJavelinConfig config__ = new JdbcJavelinConfig(); <add> <add> private static JavelinConfig logArgsConfig__ = new JavelinConfig() <add> { <add> public boolean isLogArgs() <add> { <add> return true; <add> } <add> }; <add> <add> /** <add> * constructor of this class <add> */ <add> public LightweightJdbcJavelinRecorder() <add> { <add> //Do nothing <add> } <add> <add> /** <add> * JDBCJavelinのパラメータを設定する。 <add> * @param config JDBCJavelinの設定 <add> */ <add> public static void setJdbcJavelinConfig(final JdbcJavelinConfig config) <add> { <add> LightweightJdbcJavelinRecorder.config__ = config; <add> } <add> <add> /** <add> * 設定を取得する。 <add> * <add> * @return 設定。 <add> */ <add> public static JdbcJavelinConfig getConfig() <add> { <add> return config__; <add> } <add> <add> /** <add> * <add> * @param stmt Statement object <add> */ <add> public static void preProcess(Statement stmt) <add> { <add> JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); <add> <add> if (jdbcJvnStatus.getCallDepth() == 0) <add> { <add> jdbcJvnStatus.clearPreprocessedDepthSet(); <add> } <add> <add> try <add> { <add> String jdbcUrl = "DB-Server"; <add> Connection connection = stmt.getConnection(); <add> JdbcJavelinConnection jvnConnection = null; <add> if (connection != null) <add> { <add> jvnConnection = (JdbcJavelinConnection)connection; <add> jdbcUrl = getJdbcUrl(connection, jvnConnection); <add> } <add> String className = jdbcUrl; <add> Boolean noSql = Boolean.FALSE; <add> <add> jdbcJvnStatus.setNoSql(noSql); <add> <add> CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); <add> CallTree callTree = callTreeRecorder.getCallTree(); <add> <add> execNoDuplicateCall(jdbcJvnStatus, callTreeRecorder, callTree); <add> jdbcJvnStatus.savePreprocessDepth(); <add> <add> // StatsJavelinRecorderに処理を委譲する <add> StatsJavelinRecorder.preProcess(className, "sql", null, logArgsConfig__, true); <add> } <add> catch (Exception ex) <add> { <add> // 想定外の例外が発生した場合は標準エラー出力に出力しておく。 <add> SystemLogger.getInstance().warn(ex); <add> } <add> finally <add> { <add> jdbcJvnStatus.incrementCallDepth(); <add> } <add> } <add> <add> private static String getJdbcUrl(Connection connection, JdbcJavelinConnection jvnConnection) <add> throws SQLException <add> { <add> String jdbcUrl; <add> jdbcUrl = jvnConnection.getJdbcUrl(); <add> if (jdbcUrl == null) <add> { <add> DatabaseMetaData metaData = connection.getMetaData(); <add> if (metaData != null) <add> { <add> jdbcUrl = metaData.getURL(); <add> jvnConnection.setJdbcUrl(jdbcUrl); <add> } <add> } <add> return jdbcUrl; <add> } <add> <add> private static void execNoDuplicateCall(JdbcJvnStatus jdbcJvnStatus, <add> CallTreeRecorder callTreeRecorder, CallTree tree) <add> { <add> int depth = jdbcJvnStatus.incrementDepth(); <add> if (depth > 1) <add> { <add> CallTreeNode node = callTreeRecorder.getCallTreeNode(); <add> CallTreeNode parent = node.getParent(); <add> if (parent != null) <add> { <add> callTreeRecorder.removeChildNode(parent, node); <add> } <add> else <add> { <add> // 親ノードがルートの場合は、ルートを null にする <add> tree.setRootNode(null); <add> } <add> callTreeRecorder.setCallerNode(parent); <add> } <add> } <add> <add> /** <add> * 後処理(本処理成功時)。 <add> * <add> */ <add> public static void postProcessOK() <add> { <add> JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); <add> try <add> { <add> jdbcJvnStatus.decrementCallDepth(); <add> <add> // 実行計画取得中であれば、前処理・後処理は行わない。 <add> if (jdbcJvnStatus.getNowExpalaining() != null) <add> { <add> return; <add> } <add> <add> try <add> { <add> boolean result = ignore(jdbcJvnStatus); <add> if (result == true) <add> { <add> jdbcJvnStatus.removePreProcessDepth(); <add> return; <add> } <add> } <add> catch (Exception ex) <add> { <add> SystemLogger.getInstance().warn(ex); <add> } <add> <add> if (jdbcJvnStatus.isPreprocessDepth() == false) <add> { <add> return; <add> } <add> jdbcJvnStatus.removePreProcessDepth(); <add> <add> // SQLトレース取得中状態以外の場合は、実行計画は取得しない。 <add> CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); <add> CallTree tree = callTreeRecorder.getCallTree(); <add> CallTreeNode node = null; <add> if (tree == null || (config__.isAllowSqlTraceForOracle() // <add> && (tree.containsFlag(SqlTraceStatus.KEY_SESSION_INITIALIZING) // <add> || tree.containsFlag(SqlTraceStatus.KEY_SESSION_CLOSING) // <add> || tree.containsFlag(SqlTraceStatus.KEY_SESSION_FINISHED)))) <add> { <add> return; <add> } <add> <add> // 呼び出し元情報取得。 <add> node = callTreeRecorder.getCallTreeNode(); <add> <add> // オリジナルのargsへの参照をローカル変数に一時保存 <add> String[] oldArgs = node.getArgs(); <add> if (oldArgs == null) <add> { <add> oldArgs = new String[0]; <add> } <add> <add> // SQL呼び出し回数をrootのCallTreeNodeに保持する <add> if (config__.isSqlcountMonitor()) <add> { <add> RecordStrategy rs = getRecordStrategy(tree, EventConstants.NAME_SQLCOUNT); <add> if (rs != null && rs instanceof SqlCountStrategy && oldArgs.length > 0) <add> { <add> // SQLCountStrategyのSQL呼び出し回数を増加させる <add> SqlCountStrategy strategy = (SqlCountStrategy)rs; <add> strategy.incrementSQLCount(oldArgs[0]); <add> } <add> } <add> <add> } <add> catch (Exception ex) <add> { <add> SystemLogger.getInstance().warn(ex); <add> } <add> finally <add> { <add> StatsJavelinRecorder.postProcess(null, null, (Object)null, config__, true); <add> jdbcJvnStatus.setExecPlanSql(null); <add> } <add> } <add> <add> private static boolean ignore(JdbcJvnStatus jdbcJvnStatus) <add> { <add> boolean result = false; <add> if (Boolean.TRUE.equals(jdbcJvnStatus.isNoSql())) <add> { <add> Boolean noSql = Boolean.FALSE; <add> jdbcJvnStatus.setNoSql(noSql); <add> result = true; <add> } <add> else <add> { <add> // JDBC呼出し重複出力フラグがOFF、かつ最深ノードでなければ、 <add> // 何もしない。 <add> int depth = jdbcJvnStatus.getDepth(); <add> if (config__.isRecordDuplJdbcCall() == false && depth > 0) <add> { <add> jdbcJvnStatus.decrementDepth(); <add> if (depth < jdbcJvnStatus.getDepthMax()) <add> { <add> result = true; <add> } <add> } <add> } <add> <add> return result; <add> } <add> <add> private static RecordStrategy getRecordStrategy(CallTree callTree, String strategyKey) <add> { <add> RecordStrategy rs = callTree.getRecordStrategy(strategyKey); <add> if (rs == null) <add> { <add> if (EventConstants.NAME_SQLCOUNT.equals(strategyKey)) <add> { <add> // SQLCountStrategyが登録されていない場合は、新規に登録する <add> rs = new SqlCountStrategy(); <add> callTree.addRecordStrategy(strategyKey, rs); <add> } <add> else if (SqlPlanStrategy.KEY.equals(strategyKey)) <add> { <add> // SQLPlanStrategyが登録されていない場合は、新規に登録する <add> rs = new SqlPlanStrategy(); <add> callTree.addRecordStrategy(strategyKey, rs); <add> } <add> } <add> return rs; <add> } <add> <add> /** <add> * 後処理(本処理失敗時)。 <add> * <add> */ <add> public static void postProcessNG(final Throwable cause) <add> { <add> try <add> { <add> JdbcJvnStatus jdbcJvnStatus = JdbcJvnStatus.getInstance(); <add> CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); <add> CallTree tree = callTreeRecorder.getCallTree(); <add> <add> if (tree.isJdbcEnabled() == false) <add> { <add> return; <add> } <add> <add> jdbcJvnStatus.decrementCallDepth(); <add> <add> // 実行計画取得中であれば、前処理・後処理は行わない。 <add> if (jdbcJvnStatus.getNowExpalaining() != null) <add> { <add> return; <add> } <add> <add> // セッション終了処理に入っている場合は、実行計画は取得しない。 <add> if ((config__.isAllowSqlTraceForOracle() // <add> && (tree.containsFlag(SqlTraceStatus.KEY_SESSION_INITIALIZING) // <add> || tree.containsFlag(SqlTraceStatus.KEY_SESSION_CLOSING) // <add> || tree.containsFlag(SqlTraceStatus.KEY_SESSION_FINISHED)))) <add> { <add> return; <add> } <add> <add> if (jdbcJvnStatus.isPreprocessDepth() == false) <add> { <add> return; <add> } <add> jdbcJvnStatus.removePreProcessDepth(); <add> <add> try <add> { <add> // 親ノードが"DB-Server"、かつJDBC呼出し重複出力フラグがOFFなら処理を終了。 <add> if (ignore(jdbcJvnStatus)) <add> { <add> return; <add> } <add> } <add> catch (Exception ex) <add> { <add> SystemLogger.getInstance().warn(ex); <add> } <add> <add> recordPostNG(cause, jdbcJvnStatus); <add> } <add> catch (Exception ex) <add> { <add> SystemLogger.getInstance().warn(ex); <add> } <add> finally <add> { <add> StatsJavelinRecorder.postProcess(null, null, cause, config__, true); <add> } <add> } <add> <add> public static void recordPostNG(final Throwable cause, JdbcJvnStatus jdbcJvnStatus) <add> { <add> // JavelinRecorderに処理委譲 <add> CallTreeRecorder callTreeRecorder = jdbcJvnStatus.getCallTreeRecorder(); <add> CallTreeNode node = callTreeRecorder.getCallTreeNode(); <add> if (node != null) <add> { <add> StatsJavelinRecorder.postProcess(null, null, cause, config__, true); <add> jdbcJvnStatus.setExecPlanSql(null); <add> } <add> } <add>}
Java
epl-1.0
56a2aaa4b1b27ef359cf104b29e301bfcd626964
0
stzilli/kapua,stzilli/kapua,stzilli/kapua,stzilli/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,stzilli/kapua
/******************************************************************************* * Copyright (c) 2011, 2018 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.client.tabs.permission; import com.extjs.gxt.ui.client.event.SelectionChangedEvent; import com.extjs.gxt.ui.client.event.SelectionChangedListener; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.form.CheckBox; import com.extjs.gxt.ui.client.widget.form.CheckBoxGroup; import com.extjs.gxt.ui.client.widget.form.ComboBox; import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction; import com.extjs.gxt.ui.client.widget.form.SimpleComboBox; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.rpc.AsyncCallback; import org.eclipse.kapua.app.console.module.api.client.ui.dialog.entity.EntityAddEditDialog; import org.eclipse.kapua.app.console.module.api.client.ui.panel.FormPanel; import org.eclipse.kapua.app.console.module.api.client.util.DialogUtils; import org.eclipse.kapua.app.console.module.api.shared.model.GwtSession; import org.eclipse.kapua.app.console.module.authorization.client.messages.ConsolePermissionMessages; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessInfo; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessPermission; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessPermissionCreator; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtDomain; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtGroup; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtPermission; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtPermission.GwtAction; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessInfoService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessInfoServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessPermissionService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessPermissionServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtDomainService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtDomainServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtGroupService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtGroupServiceAsync; import java.util.List; public class PermissionAddDialog extends EntityAddEditDialog { private final static ConsolePermissionMessages MSGS = GWT.create(ConsolePermissionMessages.class); private final static GwtDomainServiceAsync GWT_DOMAIN_SERVICE = GWT.create(GwtDomainService.class); private final static GwtAccessPermissionServiceAsync GWT_ACCESS_PERMISSION_SERVICE = GWT.create(GwtAccessPermissionService.class); private final static GwtAccessInfoServiceAsync GWT_ACCESS_INFO_SERVICE = GWT.create(GwtAccessInfoService.class); private final static GwtGroupServiceAsync GWT_GROUP_SERVICE = GWT.create(GwtGroupService.class); private ComboBox<GwtDomain> domainsCombo; private SimpleComboBox<GwtAction> actionsCombo; private ComboBox<GwtGroup> groupsCombo; private CheckBoxGroup forwardableChecboxGroup; private CheckBox forwardableChecbox; private final GwtGroup allGroup; private final GwtDomain allDomain = new GwtDomain("ALL"); private final GwtAction allAction = GwtAction.ALL; private String accessInfoId; public PermissionAddDialog(GwtSession currentSession, String userId) { super(currentSession); allGroup = new GwtGroup(); allGroup.setId(null); allGroup.setGroupName("ALL"); GWT_ACCESS_INFO_SERVICE.findByUserIdOrCreate(currentSession.getSelectedAccountId(), userId, new AsyncCallback<GwtAccessInfo>() { @Override public void onSuccess(GwtAccessInfo result) { accessInfoId = result.getId(); submitButton.enable(); } @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorAccessInfo(caught.getLocalizedMessage()); exitStatus = false; hide(); } }); DialogUtils.resizeDialog(this, 500, 220); } @Override public void submit() { GwtPermission newPermission = new GwtPermission(// domainsCombo.getValue().getDomainName(), // actionsCombo.getValue().getValue(), // currentSession.getSelectedAccountId(), // groupsCombo.getValue().getId(), // forwardableChecboxGroup.getValue() != null); GwtAccessPermissionCreator gwtAccessPermissionCreator = new GwtAccessPermissionCreator(); gwtAccessPermissionCreator.setScopeId(currentSession.getSelectedAccountId()); gwtAccessPermissionCreator.setAccessInfoId(accessInfoId); gwtAccessPermissionCreator.setPermission(newPermission); GWT_ACCESS_PERMISSION_SERVICE.create(xsrfToken, gwtAccessPermissionCreator, new AsyncCallback<GwtAccessPermission>() { @Override public void onSuccess(GwtAccessPermission gwtAccessPermission) { exitStatus = true; exitMessage = MSGS.dialogAddPermissionConfirmation(); // TODO Localize hide(); } @Override public void onFailure(Throwable cause) { unmask(); submitButton.enable(); cancelButton.enable(); status.hide(); exitStatus = false; exitMessage = MSGS.dialogAddError(MSGS.dialogAddPermissionError(cause.getLocalizedMessage())); hide(); } }); } @Override public String getHeaderMessage() { return MSGS.dialogAddPermissionHeader(); } @Override public String getInfoMessage() { return MSGS.dialogAddPermissionInfo(); } @Override public void createBody() { FormPanel permissionFormPanel = new FormPanel(FORM_LABEL_WIDTH); // // Domain domainsCombo = new ComboBox<GwtDomain>(); domainsCombo.setStore(new ListStore<GwtDomain>()); domainsCombo.setEditable(false); domainsCombo.setTypeAhead(false); domainsCombo.setAllowBlank(false); domainsCombo.disable(); domainsCombo.setFieldLabel(MSGS.dialogAddPermissionDomain()); domainsCombo.setTriggerAction(TriggerAction.ALL); domainsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); domainsCombo.setDisplayField("domainName"); GWT_DOMAIN_SERVICE.findAll(new AsyncCallback<List<GwtDomain>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorDomains(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtDomain> result) { domainsCombo.getStore().add(allDomain); domainsCombo.getStore().add(result); domainsCombo.setValue(allDomain); domainsCombo.enable(); } }); domainsCombo.addSelectionChangedListener(new SelectionChangedListener<GwtDomain>() { @Override public void selectionChanged(SelectionChangedEvent<GwtDomain> se) { final GwtDomain selectedDomain = se.getSelectedItem(); GWT_DOMAIN_SERVICE.findActionsByDomainName(selectedDomain.getDomainName(), new AsyncCallback<List<GwtAction>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorActions(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtAction> result) { actionsCombo.removeAll(); actionsCombo.add(allAction); actionsCombo.add(result); actionsCombo.setSimpleValue(allAction); actionsCombo.enable(); if (allDomain.equals(selectedDomain)) { groupsCombo.setEnabled(true); groupsCombo.setValue(allGroup); } else if (selectedDomain.getGroupable()) { groupsCombo.setEnabled(selectedDomain.getGroupable()); groupsCombo.setValue(allGroup); } else { groupsCombo.setEnabled(selectedDomain.getGroupable()); groupsCombo.setRawValue(MSGS.dialogAddPermissionGroupIdNotGroupable()); } } }); } }); permissionFormPanel.add(domainsCombo); // // Action actionsCombo = new SimpleComboBox<GwtAction>(); actionsCombo.disable(); actionsCombo.setTypeAhead(false); actionsCombo.setAllowBlank(false); actionsCombo.setFieldLabel(MSGS.dialogAddPermissionAction()); actionsCombo.setTriggerAction(TriggerAction.ALL); actionsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); permissionFormPanel.add(actionsCombo); // Groups groupsCombo = new ComboBox<GwtGroup>(); groupsCombo.setStore(new ListStore<GwtGroup>()); groupsCombo.setEditable(false); groupsCombo.setTypeAhead(false); groupsCombo.setAllowBlank(false); groupsCombo.setDisplayField("groupName"); groupsCombo.setValueField("id"); groupsCombo.setFieldLabel(MSGS.dialogAddPermissionGroupId()); groupsCombo.setTriggerAction(TriggerAction.ALL); groupsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); groupsCombo.disable(); GWT_GROUP_SERVICE.findAll(currentSession.getSelectedAccountId(), new AsyncCallback<List<GwtGroup>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorGroups(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtGroup> result) { groupsCombo.getStore().removeAll(); groupsCombo.getStore().add(allGroup); groupsCombo.getStore().add(result); groupsCombo.setValue(allGroup); groupsCombo.enable(); } }); permissionFormPanel.add(groupsCombo); // // Forwardable forwardableChecbox = new CheckBox(); forwardableChecbox.setBoxLabel(""); forwardableChecboxGroup = new CheckBoxGroup(); forwardableChecboxGroup.setFieldLabel(MSGS.dialogAddPermissionForwardable()); forwardableChecboxGroup.add(forwardableChecbox); permissionFormPanel.add(forwardableChecboxGroup); // // Add form panel to body bodyPanel.add(permissionFormPanel); } @Override protected void onRender(Element parent, int pos) { super.onRender(parent, pos); submitButton.disable(); } }
console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/client/tabs/permission/PermissionAddDialog.java
/******************************************************************************* * Copyright (c) 2011, 2017 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.client.tabs.permission; import com.extjs.gxt.ui.client.event.SelectionChangedEvent; import com.extjs.gxt.ui.client.event.SelectionChangedListener; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.form.CheckBox; import com.extjs.gxt.ui.client.widget.form.CheckBoxGroup; import com.extjs.gxt.ui.client.widget.form.ComboBox; import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction; import com.extjs.gxt.ui.client.widget.form.SimpleComboBox; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.rpc.AsyncCallback; import org.eclipse.kapua.app.console.module.api.client.ui.dialog.entity.EntityAddEditDialog; import org.eclipse.kapua.app.console.module.api.client.ui.panel.FormPanel; import org.eclipse.kapua.app.console.module.api.client.util.DialogUtils; import org.eclipse.kapua.app.console.module.api.shared.model.GwtSession; import org.eclipse.kapua.app.console.module.authorization.client.messages.ConsolePermissionMessages; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessInfo; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessPermission; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessPermissionCreator; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtDomain; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtGroup; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtPermission; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtPermission.GwtAction; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessInfoService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessInfoServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessPermissionService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtAccessPermissionServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtDomainService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtDomainServiceAsync; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtGroupService; import org.eclipse.kapua.app.console.module.authorization.shared.service.GwtGroupServiceAsync; import java.util.List; public class PermissionAddDialog extends EntityAddEditDialog { private final static ConsolePermissionMessages MSGS = GWT.create(ConsolePermissionMessages.class); private final static GwtDomainServiceAsync GWT_DOMAIN_SERVICE = GWT.create(GwtDomainService.class); private final static GwtAccessPermissionServiceAsync GWT_ACCESS_PERMISSION_SERVICE = GWT.create(GwtAccessPermissionService.class); private final static GwtAccessInfoServiceAsync GWT_ACCESS_INFO_SERVICE = GWT.create(GwtAccessInfoService.class); private final static GwtGroupServiceAsync GWT_GROUP_SERVICE = GWT.create(GwtGroupService.class); private ComboBox<GwtDomain> domainsCombo; private SimpleComboBox<GwtAction> actionsCombo; private ComboBox<GwtGroup> groupsCombo; private CheckBoxGroup forwardableChecboxGroup; private CheckBox forwardableChecbox; private final GwtGroup allGroup; private final GwtDomain allDomain = new GwtDomain("ALL"); private final GwtAction allAction = GwtAction.ALL; private String accessInfoId; public PermissionAddDialog(GwtSession currentSession, String userId) { super(currentSession); allGroup = new GwtGroup(); allGroup.setId(null); allGroup.setGroupName("ALL"); GWT_ACCESS_INFO_SERVICE.findByUserIdOrCreate(currentSession.getSelectedAccountId(), userId, new AsyncCallback<GwtAccessInfo>() { @Override public void onSuccess(GwtAccessInfo result) { accessInfoId = result.getId(); submitButton.enable(); } @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorAccessInfo(caught.getLocalizedMessage()); exitStatus = false; hide(); } }); DialogUtils.resizeDialog(this, 500, 220); } @Override public void submit() { GwtPermission newPermission = new GwtPermission(// domainsCombo.getValue().getDomainName(), // actionsCombo.getValue().getValue(), // currentSession.getSelectedAccountId(), // groupsCombo.getValue().getId(), // forwardableChecboxGroup.getValue() != null); GwtAccessPermissionCreator gwtAccessPermissionCreator = new GwtAccessPermissionCreator(); gwtAccessPermissionCreator.setScopeId(currentSession.getSelectedAccountId()); gwtAccessPermissionCreator.setAccessInfoId(accessInfoId); gwtAccessPermissionCreator.setPermission(newPermission); GWT_ACCESS_PERMISSION_SERVICE.create(xsrfToken, gwtAccessPermissionCreator, new AsyncCallback<GwtAccessPermission>() { @Override public void onSuccess(GwtAccessPermission gwtAccessPermission) { exitStatus = true; exitMessage = MSGS.dialogAddPermissionConfirmation(); // TODO Localize hide(); } @Override public void onFailure(Throwable cause) { unmask(); submitButton.enable(); cancelButton.enable(); status.hide(); exitStatus = false; exitMessage = MSGS.dialogAddError(MSGS.dialogAddPermissionError(cause.getLocalizedMessage())); hide(); } }); } @Override public String getHeaderMessage() { return MSGS.dialogAddPermissionHeader(); } @Override public String getInfoMessage() { return MSGS.dialogAddPermissionInfo(); } @Override public void createBody() { FormPanel permissionFormPanel = new FormPanel(FORM_LABEL_WIDTH); // // Domain domainsCombo = new ComboBox<GwtDomain>(); domainsCombo.setStore(new ListStore<GwtDomain>()); domainsCombo.setEditable(false); domainsCombo.setTypeAhead(false); domainsCombo.setAllowBlank(false); domainsCombo.disable(); domainsCombo.setFieldLabel(MSGS.dialogAddPermissionDomain()); domainsCombo.setTriggerAction(TriggerAction.ALL); domainsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); domainsCombo.setDisplayField("domainName"); GWT_DOMAIN_SERVICE.findAll(new AsyncCallback<List<GwtDomain>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorDomains(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtDomain> result) { domainsCombo.getStore().add(allDomain); domainsCombo.getStore().add(result); domainsCombo.setValue(allDomain); domainsCombo.enable(); } }); domainsCombo.addSelectionChangedListener(new SelectionChangedListener<GwtDomain>() { @Override public void selectionChanged(SelectionChangedEvent<GwtDomain> se) { final GwtDomain selectedDomain = se.getSelectedItem(); GWT_DOMAIN_SERVICE.findActionsByDomainName(selectedDomain.getDomainName(), new AsyncCallback<List<GwtAction>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorActions(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtAction> result) { actionsCombo.removeAll(); actionsCombo.add(allAction); actionsCombo.add(result); actionsCombo.setSimpleValue(allAction); actionsCombo.enable(); if (selectedDomain.getGroupable()) { groupsCombo.setEnabled(selectedDomain.getGroupable()); groupsCombo.setValue(allGroup); } else { groupsCombo.setEnabled(selectedDomain.getGroupable()); groupsCombo.setRawValue(MSGS.dialogAddPermissionGroupIdNotGroupable()); } } }); } }); permissionFormPanel.add(domainsCombo); // // Action actionsCombo = new SimpleComboBox<GwtAction>(); actionsCombo.disable(); actionsCombo.setTypeAhead(false); actionsCombo.setAllowBlank(false); actionsCombo.setFieldLabel(MSGS.dialogAddPermissionAction()); actionsCombo.setTriggerAction(TriggerAction.ALL); actionsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); permissionFormPanel.add(actionsCombo); // Groups groupsCombo = new ComboBox<GwtGroup>(); groupsCombo.setStore(new ListStore<GwtGroup>()); groupsCombo.setEditable(false); groupsCombo.setTypeAhead(false); groupsCombo.setAllowBlank(false); groupsCombo.setDisplayField("groupName"); groupsCombo.setValueField("id"); groupsCombo.setFieldLabel(MSGS.dialogAddPermissionGroupId()); groupsCombo.setTriggerAction(TriggerAction.ALL); groupsCombo.setEmptyText(MSGS.dialogAddPermissionLoading()); groupsCombo.disable(); GWT_GROUP_SERVICE.findAll(currentSession.getSelectedAccountId(), new AsyncCallback<List<GwtGroup>>() { @Override public void onFailure(Throwable caught) { exitMessage = MSGS.dialogAddPermissionErrorGroups(caught.getLocalizedMessage()); exitStatus = false; hide(); } @Override public void onSuccess(List<GwtGroup> result) { groupsCombo.getStore().removeAll(); groupsCombo.getStore().add(allGroup); groupsCombo.getStore().add(result); groupsCombo.setValue(allGroup); groupsCombo.enable(); } }); permissionFormPanel.add(groupsCombo); // // Forwardable forwardableChecbox = new CheckBox(); forwardableChecbox.setBoxLabel(""); forwardableChecboxGroup = new CheckBoxGroup(); forwardableChecboxGroup.setFieldLabel(MSGS.dialogAddPermissionForwardable()); forwardableChecboxGroup.add(forwardableChecbox); permissionFormPanel.add(forwardableChecboxGroup); // // Add form panel to body bodyPanel.add(permissionFormPanel); } @Override protected void onRender(Element parent, int pos) { super.onRender(parent, pos); submitButton.disable(); } }
access group combo fix (#1391) Signed-off-by: Bojan Utkovic <[email protected]>
console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/client/tabs/permission/PermissionAddDialog.java
access group combo fix (#1391)
<ide><path>onsole/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/client/tabs/permission/PermissionAddDialog.java <ide> /******************************************************************************* <del> * Copyright (c) 2011, 2017 Eurotech and/or its affiliates and others <add> * Copyright (c) 2011, 2018 Eurotech and/or its affiliates and others <ide> * <ide> * All rights reserved. This program and the accompanying materials <ide> * are made available under the terms of the Eclipse Public License v1.0 <ide> actionsCombo.setSimpleValue(allAction); <ide> actionsCombo.enable(); <ide> <del> if (selectedDomain.getGroupable()) { <add> if (allDomain.equals(selectedDomain)) { <add> groupsCombo.setEnabled(true); <add> groupsCombo.setValue(allGroup); <add> } else if (selectedDomain.getGroupable()) { <ide> groupsCombo.setEnabled(selectedDomain.getGroupable()); <ide> groupsCombo.setValue(allGroup); <del> <ide> } else { <ide> groupsCombo.setEnabled(selectedDomain.getGroupable()); <ide> groupsCombo.setRawValue(MSGS.dialogAddPermissionGroupIdNotGroupable());
Java
apache-2.0
6d425039c8bf0f3ddf8aa7bd35a4bfb268c2adde
0
kidaa/incubator-groovy,adjohnson916/groovy-core,paulk-asert/incubator-groovy,nkhuyu/incubator-groovy,aaronzirbes/incubator-groovy,christoph-frick/groovy-core,bsideup/groovy-core,kenzanmedia/incubator-groovy,rlovtangen/groovy-core,genqiang/incubator-groovy,samanalysis/incubator-groovy,ChanJLee/incubator-groovy,shils/groovy,paulk-asert/incubator-groovy,shils/incubator-groovy,paplorinc/incubator-groovy,pledbrook/incubator-groovy,samanalysis/incubator-groovy,avafanasiev/groovy,armsargis/groovy,alien11689/groovy-core,ebourg/incubator-groovy,ebourg/incubator-groovy,rlovtangen/groovy-core,paulk-asert/incubator-groovy,paulk-asert/incubator-groovy,rabbitcount/incubator-groovy,alien11689/incubator-groovy,adjohnson916/groovy-core,paulk-asert/groovy,russel/groovy,apache/groovy,bsideup/incubator-groovy,ebourg/incubator-groovy,avafanasiev/groovy,jwagenleitner/groovy,ChanJLee/incubator-groovy,graemerocher/incubator-groovy,kenzanmedia/incubator-groovy,adjohnson916/incubator-groovy,eginez/incubator-groovy,kenzanmedia/incubator-groovy,PascalSchumacher/incubator-groovy,tkruse/incubator-groovy,dpolivaev/groovy,jwagenleitner/incubator-groovy,kidaa/incubator-groovy,alien11689/incubator-groovy,kidaa/incubator-groovy,christoph-frick/groovy-core,genqiang/incubator-groovy,adjohnson916/groovy-core,upadhyayap/incubator-groovy,paplorinc/incubator-groovy,aim-for-better/incubator-groovy,adjohnson916/incubator-groovy,adjohnson916/groovy-core,avafanasiev/groovy,ChanJLee/incubator-groovy,aim-for-better/incubator-groovy,bsideup/groovy-core,apache/incubator-groovy,dpolivaev/groovy,sagarsane/groovy-core,dpolivaev/groovy,yukangguo/incubator-groovy,shils/incubator-groovy,nkhuyu/incubator-groovy,taoguan/incubator-groovy,groovy/groovy-core,traneHead/groovy-core,russel/incubator-groovy,bsideup/groovy-core,russel/groovy,jwagenleitner/groovy,sagarsane/groovy-core,guangying945/incubator-groovy,taoguan/incubator-groovy,EPadronU/incubator-groovy,sagarsane/incubator-groovy,groovy/groovy-core,pickypg/incubator-groovy,bsideup/incubator-groovy,aaronzirbes/incubator-groovy,russel/groovy,russel/incubator-groovy,groovy/groovy-core,graemerocher/incubator-groovy,groovy/groovy-core,jwagenleitner/groovy,rlovtangen/groovy-core,adjohnson916/incubator-groovy,alien11689/groovy-core,apache/incubator-groovy,pledbrook/incubator-groovy,ChanJLee/incubator-groovy,graemerocher/incubator-groovy,traneHead/groovy-core,gillius/incubator-groovy,aim-for-better/incubator-groovy,alien11689/groovy-core,yukangguo/incubator-groovy,PascalSchumacher/incubator-groovy,shils/incubator-groovy,graemerocher/incubator-groovy,shils/groovy,christoph-frick/groovy-core,traneHead/groovy-core,yukangguo/incubator-groovy,EPadronU/incubator-groovy,mariogarcia/groovy-core,apache/groovy,samanalysis/incubator-groovy,sagarsane/groovy-core,antoaravinth/incubator-groovy,nobeans/incubator-groovy,guangying945/incubator-groovy,armsargis/groovy,avafanasiev/groovy,aaronzirbes/incubator-groovy,alien11689/incubator-groovy,paplorinc/incubator-groovy,mariogarcia/groovy-core,ebourg/groovy-core,jwagenleitner/groovy,adjohnson916/incubator-groovy,shils/groovy,paplorinc/incubator-groovy,samanalysis/incubator-groovy,yukangguo/incubator-groovy,mariogarcia/groovy-core,nobeans/incubator-groovy,tkruse/incubator-groovy,sagarsane/incubator-groovy,shils/groovy,tkruse/incubator-groovy,ebourg/groovy-core,nobeans/incubator-groovy,rabbitcount/incubator-groovy,ebourg/groovy-core,nobeans/incubator-groovy,christoph-frick/groovy-core,paulk-asert/groovy,PascalSchumacher/incubator-groovy,kidaa/incubator-groovy,shils/incubator-groovy,tkruse/incubator-groovy,eginez/incubator-groovy,pledbrook/incubator-groovy,pickypg/incubator-groovy,eginez/incubator-groovy,EPadronU/incubator-groovy,upadhyayap/incubator-groovy,fpavageau/groovy,adjohnson916/groovy-core,ebourg/incubator-groovy,alien11689/groovy-core,bsideup/incubator-groovy,christoph-frick/groovy-core,rabbitcount/incubator-groovy,i55ac/incubator-groovy,EPadronU/incubator-groovy,alien11689/incubator-groovy,gillius/incubator-groovy,gillius/incubator-groovy,guangying945/incubator-groovy,antoaravinth/incubator-groovy,pickypg/incubator-groovy,apache/groovy,kenzanmedia/incubator-groovy,genqiang/incubator-groovy,mariogarcia/groovy-core,aim-for-better/incubator-groovy,traneHead/groovy-core,rlovtangen/groovy-core,rlovtangen/groovy-core,apache/groovy,pickypg/incubator-groovy,taoguan/incubator-groovy,paulk-asert/incubator-groovy,i55ac/incubator-groovy,i55ac/incubator-groovy,sagarsane/incubator-groovy,paulk-asert/groovy,sagarsane/incubator-groovy,jwagenleitner/incubator-groovy,eginez/incubator-groovy,antoaravinth/incubator-groovy,bsideup/incubator-groovy,groovy/groovy-core,ebourg/groovy-core,fpavageau/groovy,pledbrook/incubator-groovy,dpolivaev/groovy,armsargis/groovy,apache/incubator-groovy,PascalSchumacher/incubator-groovy,armsargis/groovy,upadhyayap/incubator-groovy,upadhyayap/incubator-groovy,sagarsane/groovy-core,paulk-asert/groovy,bsideup/groovy-core,mariogarcia/groovy-core,PascalSchumacher/incubator-groovy,fpavageau/groovy,antoaravinth/incubator-groovy,i55ac/incubator-groovy,apache/incubator-groovy,nkhuyu/incubator-groovy,nkhuyu/incubator-groovy,rabbitcount/incubator-groovy,sagarsane/groovy-core,aaronzirbes/incubator-groovy,fpavageau/groovy,guangying945/incubator-groovy,jwagenleitner/incubator-groovy,jwagenleitner/incubator-groovy,gillius/incubator-groovy,alien11689/groovy-core,russel/groovy,russel/incubator-groovy,genqiang/incubator-groovy,russel/incubator-groovy,taoguan/incubator-groovy,ebourg/groovy-core
/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.HashMap; import java.util.Map; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.StatementMeta; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; import static org.codehaus.groovy.ast.ClassHelper.*; /** * This class is for internal use only! * This class will dispatch to the right type adapters according to the * kind of binary expression that is provided. * @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a> */ public class BinaryExpressionMultiTypeDispatcher extends BinaryExpressionHelper { private static class DummyHelper extends BinaryExpressionWriter { public DummyHelper(WriterController controller) { super(controller); } @Override public boolean writePostOrPrefixMethod(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean write(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean arrayGet(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean arraySet(boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override protected void doubleTwoOperands(MethodVisitor mv) {} @Override protected MethodCaller getArrayGetCaller() { return null; } @Override protected MethodCaller getArraySetCaller() { return null; } @Override protected int getBitwiseOperationBytecode(int type) { return -1; } @Override protected int getCompareCode() { return -1; } @Override protected ClassNode getNormalOpResultType() { return null; } @Override protected int getShiftOperationBytecode(int type) { return -1; } @Override protected int getStandardOperationBytecode(int type) { return -1; } @Override protected void removeTwoOperands(MethodVisitor mv) {} @Override protected void writePlusPlus(MethodVisitor mv) {} @Override protected void writeMinusMinus(MethodVisitor mv) {} } private static class BinaryCharExpressionHelper extends BinaryIntExpressionHelper { public BinaryCharExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller charArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "cArrayGet"), charArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "cArraySet"); @Override protected MethodCaller getArrayGetCaller() { return charArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.char_TYPE; } @Override protected MethodCaller getArraySetCaller() { return charArraySet; } } private static class BinaryByteExpressionHelper extends BinaryIntExpressionHelper { public BinaryByteExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller byteArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "bArrayGet"), byteArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "bArraySet"); @Override protected MethodCaller getArrayGetCaller() { return byteArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.byte_TYPE; } @Override protected MethodCaller getArraySetCaller() { return byteArraySet; } } private static class BinaryShortExpressionHelper extends BinaryIntExpressionHelper { public BinaryShortExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller shortArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "sArrayGet"), shortArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "sArraySet"); @Override protected MethodCaller getArrayGetCaller() { return shortArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.short_TYPE; } @Override protected MethodCaller getArraySetCaller() { return shortArraySet; } } private BinaryExpressionWriter[] binExpWriter = { /* 0: dummy */ new DummyHelper(getController()), /* 1: int */ new BinaryIntExpressionHelper(getController()), /* 2: long */ new BinaryLongExpressionHelper(getController()), /* 3: double */ new BinaryDoubleExpressionHelper(getController()), /* 4: char */ new BinaryCharExpressionHelper(getController()), /* 5: byte */ new BinaryByteExpressionHelper(getController()), /* 6: short */ new BinaryShortExpressionHelper(getController()), /* 7: float */ new BinaryFloatExpressionHelper(getController()), }; private static Map<ClassNode,Integer> typeMap = new HashMap<ClassNode,Integer>(14); static { typeMap.put(int_TYPE, 1); typeMap.put(long_TYPE, 2); typeMap.put(double_TYPE, 3); typeMap.put(char_TYPE, 4); typeMap.put(byte_TYPE, 5); typeMap.put(short_TYPE, 6); typeMap.put(float_TYPE, 7); } public BinaryExpressionMultiTypeDispatcher(WriterController wc) { super(wc); } /** * return the type of an expression, taking meta data into account */ protected static ClassNode getType(Expression exp, ClassNode current) { StatementMeta meta = (StatementMeta) exp.getNodeMetaData(StatementMeta.class); ClassNode type = null; if (meta!=null) type = meta.type; if (type!=null) return type; if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.isClosureSharedVariable()) return ve.getType(); type = ve.getOriginType(); if (ve.getAccessedVariable() instanceof FieldNode) { FieldNode fn = (FieldNode) ve.getAccessedVariable(); if (!fn.getDeclaringClass().equals(current)) return OBJECT_TYPE; } } else if (exp instanceof Variable) { Variable v = (Variable) exp; type = v.getOriginType(); } else { type = exp.getType(); } return type.redirect(); } private boolean isInt(ClassNode type) { return type == int_TYPE || type == char_TYPE || type == byte_TYPE || type == short_TYPE; } private boolean isLong(ClassNode type) { return type == long_TYPE || isInt(type); } private boolean isDouble(ClassNode type) { return type == float_TYPE || type == double_TYPE || isLong(type); } private int getOperandConversionType(ClassNode leftType, ClassNode rightType) { if (isInt(leftType) && isInt(rightType)) return 1; if (isLong(leftType) && isLong(rightType)) return 2; if (isDouble(leftType) && isDouble(rightType)) return 3; return 0; } private int getOperandType(ClassNode type) { Integer ret = typeMap.get(type); if (ret==null) return 0; return ret; } @Override protected void evaluateCompareExpression(final MethodCaller compareMethod, BinaryExpression binExp) { ClassNode current = getController().getClassNode(); int operation = binExp.getOperation().getType(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.write(operation, true)) { AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateCompareExpression(compareMethod, binExp); } } @Override protected void evaluateBinaryExpression(final String message, BinaryExpression binExp) { int operation = binExp.getOperation().getType(); ClassNode current = getController().getClassNode(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); if (bew.arrayGet(operation, true)) { leftExp.visit(acg); os.doGroovyCast(leftType); rightExp.visit(acg); os.doGroovyCast(int_TYPE); bew.arrayGet(operation, false); os.doGroovyCast(bew.getArrayGetResultType()); } else if (bew.write(operation, true)) { leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateBinaryExpression(message, binExp); } } @Override protected void assignToArray(Expression orig, Expression receiver, Expression index, Expression rhsValueLoader) { ClassNode current = getController().getClassNode(); ClassNode arrayComponentType = getType(receiver, current).getComponentType(); int operationType = getOperandType(arrayComponentType); BinaryExpressionWriter bew = binExpWriter[operationType]; AsmClassGenerator acg = getController().getAcg(); if (bew.arraySet(true)) { OperandStack operandStack = getController().getOperandStack(); // load the array receiver.visit(acg); // load index index.visit(acg); operandStack.doGroovyCast(int_TYPE); // load rhs rhsValueLoader.visit(acg); operandStack.doGroovyCast(arrayComponentType); // store value in array bew.arraySet(false); // load return value && correct operand stack stack operandStack.remove(3); rhsValueLoader.visit(acg); } else { super.assignToArray(orig, receiver, index, rhsValueLoader); } } @Override protected void writePostOrPrefixMethod(int op, String method, Expression expression, Expression orig) { ClassNode type = getType(orig,getController().getClassNode()); int operationType = getOperandType(type); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.writePostOrPrefixMethod(op,true)) { OperandStack operandStack = getController().getOperandStack(); // at this point the receiver will be already on the stack operandStack.doGroovyCast(type); bew.writePostOrPrefixMethod(op,false); operandStack.replace(bew.getNormalOpResultType()); } else { super.writePostOrPrefixMethod(op, method, expression, orig); } } }
src/main/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java
/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.classgen.asm; import java.util.HashMap; import java.util.Map; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.asm.OptimizingStatementWriter.StatementMeta; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.objectweb.asm.MethodVisitor; import static org.codehaus.groovy.ast.ClassHelper.*; /** * This class is for internal use only! * This class will dispatch to the right type adapters according to the * kind of binary expression that is provided. * @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a> */ public class BinaryExpressionMultiTypeDispatcher extends BinaryExpressionHelper { private static class DummyHelper extends BinaryExpressionWriter { public DummyHelper(WriterController controller) { super(controller); } @Override public boolean writePostOrPrefixMethod(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean write(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean arrayGet(int operation, boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override public boolean arraySet(boolean simulate) { if (simulate) return false; throw new GroovyBugError("should not reach here"); } @Override protected void doubleTwoOperands(MethodVisitor mv) {} @Override protected MethodCaller getArrayGetCaller() { return null; } @Override protected MethodCaller getArraySetCaller() { return null; } @Override protected int getBitwiseOperationBytecode(int type) { return -1; } @Override protected int getCompareCode() { return -1; } @Override protected ClassNode getNormalOpResultType() { return null; } @Override protected int getShiftOperationBytecode(int type) { return -1; } @Override protected int getStandardOperationBytecode(int type) { return -1; } @Override protected void removeTwoOperands(MethodVisitor mv) {} @Override protected void writePlusPlus(MethodVisitor mv) {} @Override protected void writeMinusMinus(MethodVisitor mv) {} } private static class BinaryCharExpressionHelper extends BinaryIntExpressionHelper { public BinaryCharExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller charArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "cArrayGet"), charArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "cArraySet"); @Override protected MethodCaller getArrayGetCaller() { return charArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.char_TYPE; } @Override protected MethodCaller getArraySetCaller() { return charArraySet; } } private static class BinaryByteExpressionHelper extends BinaryIntExpressionHelper { public BinaryByteExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller byteArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "bArrayGet"), byteArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "bArraySet"); @Override protected MethodCaller getArrayGetCaller() { return byteArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.byte_TYPE; } @Override protected MethodCaller getArraySetCaller() { return byteArraySet; } } private static class BinaryShortExpressionHelper extends BinaryIntExpressionHelper { public BinaryShortExpressionHelper(WriterController wc) { super(wc); } private static final MethodCaller shortArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "sArrayGet"), shortArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "sArraySet"); @Override protected MethodCaller getArrayGetCaller() { return shortArrayGet; } @Override protected ClassNode getArrayGetResultType() { return ClassHelper.short_TYPE; } @Override protected MethodCaller getArraySetCaller() { return shortArraySet; } } private BinaryExpressionWriter[] binExpWriter = { /* 0: dummy */ new DummyHelper(getController()), /* 1: int */ new BinaryIntExpressionHelper(getController()), /* 2: long */ new BinaryLongExpressionHelper(getController()), /* 3: double */ new BinaryDoubleExpressionHelper(getController()), /* 4: char */ new BinaryCharExpressionHelper(getController()), /* 5: byte */ new BinaryByteExpressionHelper(getController()), /* 6: short */ new BinaryShortExpressionHelper(getController()), /* 7: float */ new BinaryFloatExpressionHelper(getController()), }; private static Map<ClassNode,Integer> typeMap = new HashMap<ClassNode,Integer>(14); static { typeMap.put(int_TYPE, 1); typeMap.put(long_TYPE, 2); typeMap.put(double_TYPE, 3); typeMap.put(char_TYPE, 4); typeMap.put(byte_TYPE, 5); typeMap.put(short_TYPE, 6); typeMap.put(float_TYPE, 7); } public BinaryExpressionMultiTypeDispatcher(WriterController wc) { super(wc); } /** * return the type of an expression, taking meta data into account */ protected static ClassNode getType(Expression exp, ClassNode current) { StatementMeta meta = (StatementMeta) exp.getNodeMetaData(StatementMeta.class); ClassNode type = null; if (meta!=null) type = meta.type; if (type!=null) return type; if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.isClosureSharedVariable()) return ve.getType(); type = ve.getOriginType(); if (ve.getAccessedVariable() instanceof FieldNode) { FieldNode fn = (FieldNode) ve.getAccessedVariable(); if (!fn.getDeclaringClass().equals(current)) return OBJECT_TYPE; } } else if (exp instanceof Variable) { Variable v = (Variable) exp; type = v.getOriginType(); } else { type = exp.getType(); } return type.redirect(); } private boolean isInt(ClassNode type) { return type == int_TYPE || type == char_TYPE || type == byte_TYPE || type == short_TYPE; } private boolean isLong(ClassNode type) { return type == long_TYPE || isInt(type); } private boolean isDouble(ClassNode type) { return type == float_TYPE || type == double_TYPE || isLong(type); } private int getOperandConversionType(ClassNode leftType, ClassNode rightType) { if (isInt(leftType) && isInt(rightType)) return 1; if (isLong(leftType) && isLong(rightType)) return 2; if (isDouble(leftType) && isDouble(rightType)) return 3; return 0; } private int getOperandType(ClassNode type) { Integer ret = typeMap.get(type); if (ret==null) return 0; return ret; } @Override protected void evaluateCompareExpression(final MethodCaller compareMethod, BinaryExpression binExp) { ClassNode current = getController().getClassNode(); int operation = binExp.getOperation().getType(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.write(operation, true)) { AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateCompareExpression(compareMethod, binExp); } } @Override protected void evaluateBinaryExpression(final String message, BinaryExpression binExp) { int operation = binExp.getOperation().getType(); ClassNode current = getController().getClassNode(); Expression leftExp = binExp.getLeftExpression(); ClassNode leftType = getType(leftExp, current); Expression rightExp = binExp.getRightExpression(); ClassNode rightType = getType(rightExp, current); int operationType = getOperandConversionType(leftType,rightType); BinaryExpressionWriter bew = binExpWriter[operationType]; AsmClassGenerator acg = getController().getAcg(); OperandStack os = getController().getOperandStack(); if (bew.arrayGet(operation, true)) { leftExp.visit(acg); os.doGroovyCast(leftType); rightExp.visit(acg); os.doGroovyCast(int_TYPE); bew.arrayGet(operation, false); os.doGroovyCast(bew.getArrayGetResultType()); } else if (bew.write(operation, true)) { leftExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); rightExp.visit(acg); os.doGroovyCast(bew.getNormalOpResultType()); bew.write(operation, false); } else { super.evaluateBinaryExpression(message, binExp); } } @Override protected void assignToArray(Expression orig, Expression receiver, Expression index, Expression rhsValueLoader) { ClassNode current = getController().getClassNode(); ClassNode arrayType = getType(receiver, current); int operationType = getOperandType(arrayType); BinaryExpressionWriter bew = binExpWriter[operationType]; AsmClassGenerator acg = getController().getAcg(); if (bew.arraySet(true)) { OperandStack operandStack = getController().getOperandStack(); // load the array receiver.visit(acg); // load index index.visit(acg); operandStack.doGroovyCast(int_TYPE); // load rhs rhsValueLoader.visit(acg); operandStack.doGroovyCast(arrayType); // store value in array bew.arraySet(false); // load return value && correct operand stack stack operandStack.remove(3); rhsValueLoader.visit(acg); } else { super.assignToArray(orig, receiver, index, rhsValueLoader); } } @Override protected void writePostOrPrefixMethod(int op, String method, Expression expression, Expression orig) { ClassNode type = getType(orig,getController().getClassNode()); int operationType = getOperandType(type); BinaryExpressionWriter bew = binExpWriter[operationType]; if (bew.writePostOrPrefixMethod(op,true)) { OperandStack operandStack = getController().getOperandStack(); // at this point the receiver will be already on the stack operandStack.doGroovyCast(type); bew.writePostOrPrefixMethod(op,false); operandStack.replace(bew.getNormalOpResultType()); } else { super.writePostOrPrefixMethod(op, method, expression, orig); } } }
need to use component type to get right arraySet method, because typeMap contains no array types git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@22546 a5544e8c-8a19-0410-ba12-f9af4593a198
src/main/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java
need to use component type to get right arraySet method, because typeMap contains no array types
<ide><path>rc/main/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java <ide> @Override <ide> protected void assignToArray(Expression orig, Expression receiver, Expression index, Expression rhsValueLoader) { <ide> ClassNode current = getController().getClassNode(); <del> ClassNode arrayType = getType(receiver, current); <del> int operationType = getOperandType(arrayType); <add> ClassNode arrayComponentType = getType(receiver, current).getComponentType(); <add> int operationType = getOperandType(arrayComponentType); <ide> BinaryExpressionWriter bew = binExpWriter[operationType]; <ide> AsmClassGenerator acg = getController().getAcg(); <ide> <ide> <ide> // load rhs <ide> rhsValueLoader.visit(acg); <del> operandStack.doGroovyCast(arrayType); <add> operandStack.doGroovyCast(arrayComponentType); <ide> <ide> // store value in array <ide> bew.arraySet(false);
JavaScript
mit
2d6773278f23b26c18604909e211ec06712adf1c
0
hero78119/react-i13n-ga,kaesonho/react-i13n-ga,grovelabs/react-i13n-ga
var expect = require('chai').expect; 'use strict'; describe('ga plugin client', function () { it('dummy', function () { expect(true).to.eql(true); }); });
tests/unit/index.client.js
var expect = require('chai').expect; 'use strict'; describe('ga plugin client', function () { it('dummy', function (done) { expect(true).to.be(true); }); });
fix test
tests/unit/index.client.js
fix test
<ide><path>ests/unit/index.client.js <ide> 'use strict'; <ide> <ide> describe('ga plugin client', function () { <del> it('dummy', function (done) { <del> expect(true).to.be(true); <add> it('dummy', function () { <add> expect(true).to.eql(true); <ide> }); <ide> });
Java
apache-2.0
67034a5a55d1eeaf07508c1505da8be420ae8758
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud.api.collections; import static org.apache.solr.core.TrackingBackupRepository.copiedFiles; import java.io.IOException; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.CollectionAdminResponse; import org.apache.solr.client.solrj.response.RequestStatusState; import org.apache.solr.cloud.AbstractDistribZkTestBase; import org.apache.solr.cloud.SolrCloudTestCase; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.DirectoryFactory; import org.apache.solr.core.SolrCore; import org.apache.solr.core.TrackingBackupRepository; import org.apache.solr.core.backup.BackupFilePaths; import org.apache.solr.core.backup.BackupId; import org.apache.solr.core.backup.BackupProperties; import org.apache.solr.core.backup.Checksum; import org.apache.solr.core.backup.ShardBackupId; import org.apache.solr.core.backup.ShardBackupMetadata; import org.apache.solr.core.backup.repository.BackupRepository; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to test the incremental method of backup/restoration (as opposed to the deprecated 'full * snapshot' method). * * <p>For a similar test harness for snapshot backup/restoration see {@link * AbstractCloudBackupRestoreTestCase} */ public abstract class AbstractIncrementalBackupTest extends SolrCloudTestCase { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static long docsSeed; // see indexDocs() protected static final int NUM_SHARDS = 2; // granted we sometimes shard split to get more protected static final int REPL_FACTOR = 2; protected static final String BACKUPNAME_PREFIX = "mytestbackup"; protected static final String BACKUP_REPO_NAME = "trackingBackupRepository"; protected String testSuffix = "test1"; @BeforeClass public static void createCluster() throws Exception { docsSeed = random().nextLong(); System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); } @Before public void setUpTrackingRepo() { TrackingBackupRepository.clear(); } /** * @return The name of the collection to use. */ public abstract String getCollectionNamePrefix(); public String getCollectionName() { return getCollectionNamePrefix() + "_" + testSuffix; } public void setTestSuffix(String testSuffix) { this.testSuffix = testSuffix; } /** * @return The absolute path for the backup location. Could return null. */ public abstract String getBackupLocation(); @Test public void testSimple() throws Exception { setTestSuffix("testbackupincsimple"); final String backupCollectionName = getCollectionName(); final String restoreCollectionName = backupCollectionName + "_restore"; CloudSolrClient solrClient = cluster.getSolrClient(); CollectionAdminRequest.createCollection(backupCollectionName, "conf1", NUM_SHARDS, 1) .process(solrClient); int totalIndexedDocs = indexDocs(backupCollectionName, true); String backupName = BACKUPNAME_PREFIX + testSuffix; try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { String backupLocation = repository.getBackupLocation(getBackupLocation()); long t = System.nanoTime(); int expectedDocsForFirstBackup = totalIndexedDocs; CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setIncremental(true) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 100); long timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Created backup with {} docs, took {}ms", totalIndexedDocs, timeTaken); totalIndexedDocs += indexDocs(backupCollectionName, true); t = System.nanoTime(); CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setIncremental(true) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 100); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); long numFound = cluster .getSolrClient() .query(backupCollectionName, new SolrQuery("*:*")) .getResults() .getNumFound(); log.info("Created backup with {} docs, took {}ms", numFound, timeTaken); t = System.nanoTime(); randomlyPrecreateRestoreCollection(restoreCollectionName, "conf1", NUM_SHARDS, 1); CollectionAdminRequest.restoreCollection(restoreCollectionName, backupName) .setBackupId(0) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(solrClient, 500); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Restored from backup, took {}ms", timeTaken); t = System.nanoTime(); AbstractDistribZkTestBase.waitForRecoveriesToFinish( restoreCollectionName, ZkStateReader.from(solrClient), log.isDebugEnabled(), false, 3); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Restored collection healthy, took {}ms", timeTaken); numFound = cluster .getSolrClient() .query(restoreCollectionName, new SolrQuery("*:*")) .getResults() .getNumFound(); assertEquals(expectedDocsForFirstBackup, numFound); } } @Test public void testRestoreToOriginalCollection() throws Exception { setTestSuffix("testbackuprestoretooriginal"); final String backupCollectionName = getCollectionName(); final String backupName = BACKUPNAME_PREFIX + testSuffix; // Bootstrap the backup collection with seed docs CollectionAdminRequest.createCollection(backupCollectionName, "conf1", NUM_SHARDS, REPL_FACTOR) .process(cluster.getSolrClient()); final int firstBatchNumDocs = indexDocs(backupCollectionName, true); // Backup and immediately add more docs to the collection try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { final String backupLocation = repository.getBackupLocation(getBackupLocation()); final RequestStatusState result = CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 20); assertEquals(RequestStatusState.COMPLETED, result); } final int secondBatchNumDocs = indexDocs(backupCollectionName, true); final int maxDocs = secondBatchNumDocs + firstBatchNumDocs; assertEquals(maxDocs, getNumDocsInCollection(backupCollectionName)); // Restore original docs and validate that doc count is correct try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { final String backupLocation = repository.getBackupLocation(getBackupLocation()); final RequestStatusState result = CollectionAdminRequest.restoreCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 30); assertEquals(RequestStatusState.COMPLETED, result); } assertEquals(firstBatchNumDocs, getNumDocsInCollection(backupCollectionName)); } @Test @Nightly public void testBackupIncremental() throws Exception { setTestSuffix("testbackupinc"); CloudSolrClient solrClient = cluster.getSolrClient(); CollectionAdminRequest.createCollection(getCollectionName(), "conf1", NUM_SHARDS, REPL_FACTOR) .process(solrClient); indexDocs(getCollectionName(), false); String backupName = BACKUPNAME_PREFIX + testSuffix; try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { String backupLocation = repository.getBackupLocation(getBackupLocation()); URI fullBackupLocationURI = repository.resolveDirectory( repository.createDirectoryURI(backupLocation), backupName, getCollectionName()); BackupFilePaths backupPaths = new BackupFilePaths(repository, fullBackupLocationURI); IncrementalBackupVerifier verifier = new IncrementalBackupVerifier( repository, backupLocation, backupName, getCollectionName(), 3); backupRestoreThenCheck(solrClient, verifier); indexDocs(getCollectionName(), false); backupRestoreThenCheck(solrClient, verifier); // adding more commits to trigger merging segments for (int i = 0; i < 15; i++) { indexDocs(getCollectionName(), 5, false); } backupRestoreThenCheck(solrClient, verifier); indexDocs(getCollectionName(), false); backupRestoreThenCheck(solrClient, verifier); // test list backups CollectionAdminResponse resp = CollectionAdminRequest.listBackup(backupName) .setBackupLocation(backupLocation) .setBackupRepository(BACKUP_REPO_NAME) .process(cluster.getSolrClient()); List<?> backups = (List<?>) resp.getResponse().get("backups"); assertEquals(3, backups.size()); // test delete backups resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 4) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertNull(resp.getResponse().get("deleted")); resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 3) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertNull(resp.getResponse().get("deleted")); resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 2) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(1, resp.getResponse()._get("deleted[0]/backupId", null)); resp = CollectionAdminRequest.deleteBackupById(backupName, 3) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(3, resp.getResponse()._get("deleted[0]/backupId", null)); simpleRestoreAndCheckDocCount(solrClient, backupLocation, backupName); // test purge backups // purging first since there may corrupted files were uploaded resp = CollectionAdminRequest.deleteBackupPurgeUnusedFiles(backupName) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); addDummyFileToIndex(repository, backupPaths.getIndexDir(), "dummy-files-1"); addDummyFileToIndex(repository, backupPaths.getIndexDir(), "dummy-files-2"); resp = CollectionAdminRequest.deleteBackupPurgeUnusedFiles(backupName) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(2, ((NamedList) resp.getResponse().get("deleted")).get("numIndexFiles")); new UpdateRequest().deleteByQuery("*:*").commit(cluster.getSolrClient(), getCollectionName()); indexDocs(getCollectionName(), false); // corrupt index files corruptIndexFiles(); try { log.info("Create backup after corrupt index files"); CollectionAdminRequest.Backup backup = CollectionAdminRequest.backupCollection(getCollectionName(), backupName) .setLocation(backupLocation) .setIncremental(true) .setMaxNumberBackupPoints(3) .setRepositoryName(BACKUP_REPO_NAME); if (random().nextBoolean()) { RequestStatusState state = backup.processAndWait(cluster.getSolrClient(), 1000); if (state != RequestStatusState.FAILED) { fail("This backup should be failed"); } } else { CollectionAdminResponse rsp = backup.process(cluster.getSolrClient()); fail("This backup should be failed"); } } catch (Exception e) { log.error("expected", e); } } } protected void corruptIndexFiles() throws IOException { List<Slice> slices = new ArrayList<>(getCollectionState(getCollectionName()).getSlices()); Replica leader = slices.get(random().nextInt(slices.size())).getLeader(); JettySolrRunner leaderNode = cluster.getReplicaJetty(leader); final Path fileToCorrupt; try (SolrCore solrCore = leaderNode.getCoreContainer().getCore(leader.getCoreName())) { Set<String> fileNames = new HashSet<>(solrCore.getDeletionPolicy().getLatestCommit().getFileNames()); final List<Path> indexFiles; try (Stream<Path> indexFolderFiles = Files.list(Path.of(solrCore.getIndexDir()))) { indexFiles = indexFolderFiles .filter(x -> fileNames.contains(x.getFileName().toString())) .sorted() .collect(Collectors.toList()); } if (indexFiles.isEmpty()) { return; } fileToCorrupt = indexFiles.get(random().nextInt(indexFiles.size())); } final byte[] contents = Files.readAllBytes(fileToCorrupt); for (int i = 1; i < 5; i++) { int key = contents.length - CodecUtil.footerLength() - i; if (key >= 0) { contents[key] = (byte) (contents[key] + 1); } } Files.write(fileToCorrupt, contents); } private void addDummyFileToIndex(BackupRepository repository, URI indexDir, String fileName) throws IOException { try (OutputStream os = repository.createOutput(repository.resolve(indexDir, fileName))) { os.write(100); os.write(101); os.write(102); } } private void backupRestoreThenCheck( CloudSolrClient solrClient, IncrementalBackupVerifier verifier) throws Exception { verifier.incrementalBackupThenVerify(); if (random().nextBoolean()) simpleRestoreAndCheckDocCount(solrClient, verifier.backupLocation, verifier.backupName); } private void simpleRestoreAndCheckDocCount( CloudSolrClient solrClient, String backupLocation, String backupName) throws Exception { Map<String, Integer> origShardToDocCount = AbstractCloudBackupRestoreTestCase.getShardToDocCountMap( solrClient, getCollectionState(getCollectionName())); String restoreCollectionName = getCollectionName() + "_restored"; randomlyPrecreateRestoreCollection(restoreCollectionName, "conf1", NUM_SHARDS, REPL_FACTOR); CollectionAdminRequest.restoreCollection(restoreCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .process(solrClient); AbstractDistribZkTestBase.waitForRecoveriesToFinish( restoreCollectionName, ZkStateReader.from(solrClient), log.isDebugEnabled(), true, 30); // check num docs are the same assertEquals( origShardToDocCount, AbstractCloudBackupRestoreTestCase.getShardToDocCountMap( solrClient, getCollectionState(restoreCollectionName))); // this methods may get invoked multiple times, collection must be cleanup CollectionAdminRequest.deleteCollection(restoreCollectionName).process(solrClient); } private void indexDocs(String collectionName, int numDocs, boolean useUUID) throws Exception { Random random = new Random(docsSeed); List<SolrInputDocument> docs = new ArrayList<>(numDocs); for (int i = 0; i < numDocs; i++) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", (useUUID ? java.util.UUID.randomUUID().toString() : i)); doc.addField("shard_s", "shard" + (1 + random.nextInt(NUM_SHARDS))); // for implicit router docs.add(doc); } CloudSolrClient client = cluster.getSolrClient(); client.add(collectionName, docs); // batch client.commit(collectionName); log.info("Indexed {} docs to collection: {}", numDocs, collectionName); } private int indexDocs(String collectionName, boolean useUUID) throws Exception { Random random = new Random( docsSeed); // use a constant seed for the whole test run so that we can easily re-index. int numDocs = random.nextInt(100) + 5; indexDocs(collectionName, numDocs, useUUID); return numDocs; } private void randomlyPrecreateRestoreCollection( String restoreCollectionName, String configName, int numShards, int numReplicas) throws Exception { if (random().nextBoolean()) { CollectionAdminRequest.createCollection( restoreCollectionName, configName, numShards, numReplicas) .process(cluster.getSolrClient()); cluster.waitForActiveCollection(restoreCollectionName, numShards, numShards * numReplicas); } } private long getNumDocsInCollection(String collectionName) throws Exception { return new QueryRequest(new SolrQuery("*:*")) .process(cluster.getSolrClient(), collectionName) .getResults() .getNumFound(); } private class IncrementalBackupVerifier { private BackupRepository repository; private URI backupURI; private String backupLocation; private String backupName; private BackupFilePaths incBackupFiles; private Map<String, Collection<String>> lastShardCommitToBackupFiles = new HashMap<>(); // the first generation after calling backup is zero private int numBackup = -1; private int maxNumberOfBackupToKeep = 4; IncrementalBackupVerifier( BackupRepository repository, String backupLocation, String backupName, String collection, int maxNumberOfBackupToKeep) { this.repository = repository; this.backupLocation = backupLocation; this.backupURI = repository.resolveDirectory(repository.createURI(backupLocation), backupName, collection); this.incBackupFiles = new BackupFilePaths(repository, this.backupURI); this.backupName = backupName; this.maxNumberOfBackupToKeep = maxNumberOfBackupToKeep; } @SuppressWarnings("rawtypes") private void backupThenWait() throws SolrServerException, IOException { CollectionAdminRequest.Backup backup = CollectionAdminRequest.backupCollection(getCollectionName(), backupName) .setLocation(backupLocation) .setIncremental(true) .setMaxNumberBackupPoints(maxNumberOfBackupToKeep) .setRepositoryName(BACKUP_REPO_NAME); if (random().nextBoolean()) { try { RequestStatusState state = backup.processAndWait(cluster.getSolrClient(), 1000); assertEquals(RequestStatusState.COMPLETED, state); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("interrupted", e); } numBackup++; } else { CollectionAdminResponse rsp = backup.process(cluster.getSolrClient()); assertEquals(0, rsp.getStatus()); NamedList resp = (NamedList) rsp.getResponse().get("response"); numBackup++; assertEquals(numBackup, resp.get("backupId")); ; } } void incrementalBackupThenVerify() throws IOException, SolrServerException { int numCopiedFiles = copiedFiles().size(); backupThenWait(); List<URI> newFilesCopiedOver = copiedFiles().subList(numCopiedFiles, copiedFiles().size()); verify(newFilesCopiedOver); } ShardBackupMetadata getLastShardBackupId(String shardName) throws IOException { ShardBackupId shardBackupId = BackupProperties.readFromLatest(repository, backupURI) .flatMap(bp -> bp.getShardBackupIdFor(shardName)) .get(); return ShardBackupMetadata.from( repository, new BackupFilePaths(repository, backupURI).getShardBackupMetadataDir(), shardBackupId); } private void assertIndexInputEquals(IndexInput in1, IndexInput in2) throws IOException { assertEquals(in1.length(), in2.length()); for (int i = 0; i < in1.length(); i++) { assertEquals(in1.readByte(), in2.readByte()); } } private void assertFolderAreSame(URI uri1, URI uri2) throws IOException { String[] files1 = repository.listAll(uri1); String[] files2 = repository.listAll(uri2); Arrays.sort(files1); Arrays.sort(files2); assertArrayEquals(files1, files2); for (int i = 0; i < files1.length; i++) { URI file1Uri = repository.resolve(uri1, files1[i]); URI file2Uri = repository.resolve(uri2, files2[i]); assertEquals(repository.getPathType(file1Uri), repository.getPathType(file2Uri)); if (repository.getPathType(file1Uri) == BackupRepository.PathType.DIRECTORY) { assertFolderAreSame(file1Uri, file2Uri); } else { try (IndexInput in1 = repository.openInput(uri1, files1[i], IOContext.READONCE); IndexInput in2 = repository.openInput(uri1, files1[i], IOContext.READONCE)) { assertIndexInputEquals(in1, in2); } } } } public void verify(List<URI> newFilesCopiedOver) throws IOException { // Verify zk files are reuploaded to a appropriate each time a backup is called // TODO make a little change to zk files and make sure that backed up files match with zk data BackupId prevBackupId = new BackupId(Math.max(0, numBackup - 1)); URI backupPropertiesFile = repository.resolve(backupURI, "backup_" + numBackup + ".properties"); URI zkBackupFolder = repository.resolve(backupURI, "zk_backup_" + numBackup); assertTrue(repository.exists(backupPropertiesFile)); assertTrue(repository.exists(zkBackupFolder)); assertFolderAreSame( repository.resolveDirectory(backupURI, BackupFilePaths.getZkStateDir(prevBackupId)), zkBackupFolder); // verify indexes file for (Slice slice : getCollectionState(getCollectionName()).getSlices()) { Replica leader = slice.getLeader(); final ShardBackupMetadata shardBackupMetadata = getLastShardBackupId(slice.getName()); assertNotNull(shardBackupMetadata); try (SolrCore solrCore = cluster.getReplicaJetty(leader).getCoreContainer().getCore(leader.getCoreName())) { Directory dir = solrCore .getDirectoryFactory() .get( solrCore.getIndexDir(), DirectoryFactory.DirContext.DEFAULT, solrCore.getSolrConfig().indexConfig.lockType); try { URI indexDir = incBackupFiles.getIndexDir(); IndexCommit lastCommit = solrCore.getDeletionPolicy().getLatestCommit(); Collection<String> newBackupFiles = newIndexFilesComparedToLastBackup(slice.getName(), lastCommit).stream() .map( indexFile -> { Optional<ShardBackupMetadata.BackedFile> backedFile = shardBackupMetadata.getFile(indexFile); assertTrue(backedFile.isPresent()); return backedFile.get().uniqueFileName; }) .collect(Collectors.toList()); lastCommit .getFileNames() .forEach( f -> { Optional<ShardBackupMetadata.BackedFile> backedFile = shardBackupMetadata.getFile(f); assertTrue(backedFile.isPresent()); String uniqueFileName = backedFile.get().uniqueFileName; if (newBackupFiles.contains(uniqueFileName)) { assertTrue( newFilesCopiedOver.contains( repository.resolve(indexDir, uniqueFileName))); } try { Checksum localChecksum = repository.checksum(dir, f); Checksum remoteChecksum = backedFile.get().fileChecksum; assertEquals(localChecksum.checksum, remoteChecksum.checksum); assertEquals(localChecksum.size, remoteChecksum.size); } catch (IOException e) { throw new AssertionError(e); } }); assertEquals( "Incremental backup stored more files than needed", lastCommit.getFileNames().size(), shardBackupMetadata.listOriginalFileNames().size()); } finally { solrCore.getDirectoryFactory().release(dir); } } } } private Collection<String> newIndexFilesComparedToLastBackup( String shardName, IndexCommit currentCommit) throws IOException { Collection<String> oldFiles = lastShardCommitToBackupFiles.put(shardName, currentCommit.getFileNames()); if (oldFiles == null) oldFiles = new ArrayList<>(); List<String> newFiles = new ArrayList<>(currentCommit.getFileNames()); newFiles.removeAll(oldFiles); return newFiles; } } }
solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud.api.collections; import static org.apache.solr.core.TrackingBackupRepository.copiedFiles; import java.io.IOException; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.CollectionAdminResponse; import org.apache.solr.client.solrj.response.RequestStatusState; import org.apache.solr.cloud.AbstractDistribZkTestBase; import org.apache.solr.cloud.SolrCloudTestCase; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.DirectoryFactory; import org.apache.solr.core.SolrCore; import org.apache.solr.core.TrackingBackupRepository; import org.apache.solr.core.backup.BackupFilePaths; import org.apache.solr.core.backup.BackupId; import org.apache.solr.core.backup.BackupProperties; import org.apache.solr.core.backup.Checksum; import org.apache.solr.core.backup.ShardBackupId; import org.apache.solr.core.backup.ShardBackupMetadata; import org.apache.solr.core.backup.repository.BackupRepository; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to test the incremental method of backup/restoration (as opposed to the deprecated 'full * snapshot' method). * * <p>For a similar test harness for snapshot backup/restoration see {@link * AbstractCloudBackupRestoreTestCase} */ public abstract class AbstractIncrementalBackupTest extends SolrCloudTestCase { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static long docsSeed; // see indexDocs() protected static final int NUM_SHARDS = 2; // granted we sometimes shard split to get more protected static final int REPL_FACTOR = 2; protected static final String BACKUPNAME_PREFIX = "mytestbackup"; protected static final String BACKUP_REPO_NAME = "trackingBackupRepository"; protected String testSuffix = "test1"; @BeforeClass public static void createCluster() throws Exception { docsSeed = random().nextLong(); System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); } @Before public void setUpTrackingRepo() { TrackingBackupRepository.clear(); } /** * @return The name of the collection to use. */ public abstract String getCollectionNamePrefix(); public String getCollectionName() { return getCollectionNamePrefix() + "_" + testSuffix; } public void setTestSuffix(String testSuffix) { this.testSuffix = testSuffix; } /** * @return The absolute path for the backup location. Could return null. */ public abstract String getBackupLocation(); @Test public void testSimple() throws Exception { setTestSuffix("testbackupincsimple"); final String backupCollectionName = getCollectionName(); final String restoreCollectionName = backupCollectionName + "_restore"; CloudSolrClient solrClient = cluster.getSolrClient(); CollectionAdminRequest.createCollection(backupCollectionName, "conf1", NUM_SHARDS, 1) .process(solrClient); int totalIndexedDocs = indexDocs(backupCollectionName, true); String backupName = BACKUPNAME_PREFIX + testSuffix; try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { String backupLocation = repository.getBackupLocation(getBackupLocation()); long t = System.nanoTime(); int expectedDocsForFirstBackup = totalIndexedDocs; CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setIncremental(true) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 100); long timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Created backup with {} docs, took {}ms", totalIndexedDocs, timeTaken); totalIndexedDocs += indexDocs(backupCollectionName, true); t = System.nanoTime(); CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setIncremental(true) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 100); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); long numFound = cluster .getSolrClient() .query(backupCollectionName, new SolrQuery("*:*")) .getResults() .getNumFound(); log.info("Created backup with {} docs, took {}ms", numFound, timeTaken); t = System.nanoTime(); randomlyPrecreateRestoreCollection(restoreCollectionName, "conf1", NUM_SHARDS, 1); CollectionAdminRequest.restoreCollection(restoreCollectionName, backupName) .setBackupId(0) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(solrClient, 500); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Restored from backup, took {}ms", timeTaken); t = System.nanoTime(); AbstractDistribZkTestBase.waitForRecoveriesToFinish( restoreCollectionName, ZkStateReader.from(solrClient), log.isDebugEnabled(), false, 3); timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t); log.info("Restored collection healthy, took {}ms", timeTaken); numFound = cluster .getSolrClient() .query(restoreCollectionName, new SolrQuery("*:*")) .getResults() .getNumFound(); assertEquals(expectedDocsForFirstBackup, numFound); } } @Test public void testRestoreToOriginalCollection() throws Exception { setTestSuffix("testbackuprestoretooriginal"); final String backupCollectionName = getCollectionName(); final String backupName = BACKUPNAME_PREFIX + testSuffix; // Bootstrap the backup collection with seed docs CollectionAdminRequest.createCollection(backupCollectionName, "conf1", NUM_SHARDS, REPL_FACTOR) .process(cluster.getSolrClient()); final int firstBatchNumDocs = indexDocs(backupCollectionName, true); // Backup and immediately add more docs to the collection try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { final String backupLocation = repository.getBackupLocation(getBackupLocation()); final RequestStatusState result = CollectionAdminRequest.backupCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 20); assertEquals(RequestStatusState.COMPLETED, result); } final int secondBatchNumDocs = indexDocs(backupCollectionName, true); final int maxDocs = secondBatchNumDocs + firstBatchNumDocs; assertEquals(maxDocs, getNumDocsInCollection(backupCollectionName)); // Restore original docs and validate that doc count is correct try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { final String backupLocation = repository.getBackupLocation(getBackupLocation()); final RequestStatusState result = CollectionAdminRequest.restoreCollection(backupCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .processAndWait(cluster.getSolrClient(), 30); assertEquals(RequestStatusState.COMPLETED, result); } assertEquals(firstBatchNumDocs, getNumDocsInCollection(backupCollectionName)); } @Test @Nightly public void testBackupIncremental() throws Exception { setTestSuffix("testbackupinc"); CloudSolrClient solrClient = cluster.getSolrClient(); CollectionAdminRequest.createCollection(getCollectionName(), "conf1", NUM_SHARDS, REPL_FACTOR) .process(solrClient); indexDocs(getCollectionName(), false); String backupName = BACKUPNAME_PREFIX + testSuffix; try (BackupRepository repository = cluster.getJettySolrRunner(0).getCoreContainer().newBackupRepository(BACKUP_REPO_NAME)) { String backupLocation = repository.getBackupLocation(getBackupLocation()); URI fullBackupLocationURI = repository.resolveDirectory( repository.createDirectoryURI(backupLocation), backupName, getCollectionName()); BackupFilePaths backupPaths = new BackupFilePaths(repository, fullBackupLocationURI); IncrementalBackupVerifier verifier = new IncrementalBackupVerifier( repository, backupLocation, backupName, getCollectionName(), 3); backupRestoreThenCheck(solrClient, verifier); indexDocs(getCollectionName(), false); backupRestoreThenCheck(solrClient, verifier); // adding more commits to trigger merging segments for (int i = 0; i < 15; i++) { indexDocs(getCollectionName(), 5, false); } backupRestoreThenCheck(solrClient, verifier); indexDocs(getCollectionName(), false); backupRestoreThenCheck(solrClient, verifier); // test list backups CollectionAdminResponse resp = CollectionAdminRequest.listBackup(backupName) .setBackupLocation(backupLocation) .setBackupRepository(BACKUP_REPO_NAME) .process(cluster.getSolrClient()); List<?> backups = (List<?>) resp.getResponse().get("backups"); assertEquals(3, backups.size()); // test delete backups resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 4) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertNull(resp.getResponse().get("deleted")); resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 3) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertNull(resp.getResponse().get("deleted")); resp = CollectionAdminRequest.deleteBackupByRecency(backupName, 2) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(1, resp.getResponse()._get("deleted[0]/backupId", null)); resp = CollectionAdminRequest.deleteBackupById(backupName, 3) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(3, resp.getResponse()._get("deleted[0]/backupId", null)); simpleRestoreAndCheckDocCount(solrClient, backupLocation, backupName); // test purge backups // purging first since there may corrupted files were uploaded resp = CollectionAdminRequest.deleteBackupPurgeUnusedFiles(backupName) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); addDummyFileToIndex(repository, backupPaths.getIndexDir(), "dummy-files-1"); addDummyFileToIndex(repository, backupPaths.getIndexDir(), "dummy-files-2"); resp = CollectionAdminRequest.deleteBackupPurgeUnusedFiles(backupName) .setRepositoryName(BACKUP_REPO_NAME) .setLocation(backupLocation) .process(cluster.getSolrClient()); assertEquals(2, ((NamedList) resp.getResponse().get("deleted")).get("numIndexFiles")); new UpdateRequest().deleteByQuery("*:*").commit(cluster.getSolrClient(), getCollectionName()); indexDocs(getCollectionName(), false); // corrupt index files corruptIndexFiles(); try { log.info("Create backup after corrupt index files"); CollectionAdminRequest.Backup backup = CollectionAdminRequest.backupCollection(getCollectionName(), backupName) .setLocation(backupLocation) .setIncremental(true) .setMaxNumberBackupPoints(3) .setRepositoryName(BACKUP_REPO_NAME); if (random().nextBoolean()) { RequestStatusState state = backup.processAndWait(cluster.getSolrClient(), 1000); if (state != RequestStatusState.FAILED) { fail("This backup should be failed"); } } else { CollectionAdminResponse rsp = backup.process(cluster.getSolrClient()); fail("This backup should be failed"); } } catch (Exception e) { log.error("expected", e); } } } protected void corruptIndexFiles() throws IOException { List<Slice> slices = new ArrayList<>(getCollectionState(getCollectionName()).getSlices()); Replica leader = slices.get(random().nextInt(slices.size()) - 1).getLeader(); JettySolrRunner leaderNode = cluster.getReplicaJetty(leader); final Path fileToCorrupt; try (SolrCore solrCore = leaderNode.getCoreContainer().getCore(leader.getCoreName())) { Set<String> fileNames = new HashSet<>(solrCore.getDeletionPolicy().getLatestCommit().getFileNames()); final List<Path> indexFiles; try (Stream<Path> indexFolderFiles = Files.list(Path.of(solrCore.getIndexDir()))) { indexFiles = indexFolderFiles .filter(x -> fileNames.contains(x.getFileName().toString())) .sorted() .collect(Collectors.toList()); } if (indexFiles.isEmpty()) { return; } fileToCorrupt = indexFiles.get(random().nextInt(indexFiles.size()) - 1); } final byte[] contents = Files.readAllBytes(fileToCorrupt); for (int i = 1; i < 5; i++) { int key = contents.length - CodecUtil.footerLength() - i; contents[key] = (byte) (contents[key] + 1); } Files.write(fileToCorrupt, contents); } private void addDummyFileToIndex(BackupRepository repository, URI indexDir, String fileName) throws IOException { try (OutputStream os = repository.createOutput(repository.resolve(indexDir, fileName))) { os.write(100); os.write(101); os.write(102); } } private void backupRestoreThenCheck( CloudSolrClient solrClient, IncrementalBackupVerifier verifier) throws Exception { verifier.incrementalBackupThenVerify(); if (random().nextBoolean()) simpleRestoreAndCheckDocCount(solrClient, verifier.backupLocation, verifier.backupName); } private void simpleRestoreAndCheckDocCount( CloudSolrClient solrClient, String backupLocation, String backupName) throws Exception { Map<String, Integer> origShardToDocCount = AbstractCloudBackupRestoreTestCase.getShardToDocCountMap( solrClient, getCollectionState(getCollectionName())); String restoreCollectionName = getCollectionName() + "_restored"; randomlyPrecreateRestoreCollection(restoreCollectionName, "conf1", NUM_SHARDS, REPL_FACTOR); CollectionAdminRequest.restoreCollection(restoreCollectionName, backupName) .setLocation(backupLocation) .setRepositoryName(BACKUP_REPO_NAME) .process(solrClient); AbstractDistribZkTestBase.waitForRecoveriesToFinish( restoreCollectionName, ZkStateReader.from(solrClient), log.isDebugEnabled(), true, 30); // check num docs are the same assertEquals( origShardToDocCount, AbstractCloudBackupRestoreTestCase.getShardToDocCountMap( solrClient, getCollectionState(restoreCollectionName))); // this methods may get invoked multiple times, collection must be cleanup CollectionAdminRequest.deleteCollection(restoreCollectionName).process(solrClient); } private void indexDocs(String collectionName, int numDocs, boolean useUUID) throws Exception { Random random = new Random(docsSeed); List<SolrInputDocument> docs = new ArrayList<>(numDocs); for (int i = 0; i < numDocs; i++) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", (useUUID ? java.util.UUID.randomUUID().toString() : i)); doc.addField("shard_s", "shard" + (1 + random.nextInt(NUM_SHARDS))); // for implicit router docs.add(doc); } CloudSolrClient client = cluster.getSolrClient(); client.add(collectionName, docs); // batch client.commit(collectionName); log.info("Indexed {} docs to collection: {}", numDocs, collectionName); } private int indexDocs(String collectionName, boolean useUUID) throws Exception { Random random = new Random( docsSeed); // use a constant seed for the whole test run so that we can easily re-index. int numDocs = random.nextInt(100) + 5; indexDocs(collectionName, numDocs, useUUID); return numDocs; } private void randomlyPrecreateRestoreCollection( String restoreCollectionName, String configName, int numShards, int numReplicas) throws Exception { if (random().nextBoolean()) { CollectionAdminRequest.createCollection( restoreCollectionName, configName, numShards, numReplicas) .process(cluster.getSolrClient()); cluster.waitForActiveCollection(restoreCollectionName, numShards, numShards * numReplicas); } } private long getNumDocsInCollection(String collectionName) throws Exception { return new QueryRequest(new SolrQuery("*:*")) .process(cluster.getSolrClient(), collectionName) .getResults() .getNumFound(); } private class IncrementalBackupVerifier { private BackupRepository repository; private URI backupURI; private String backupLocation; private String backupName; private BackupFilePaths incBackupFiles; private Map<String, Collection<String>> lastShardCommitToBackupFiles = new HashMap<>(); // the first generation after calling backup is zero private int numBackup = -1; private int maxNumberOfBackupToKeep = 4; IncrementalBackupVerifier( BackupRepository repository, String backupLocation, String backupName, String collection, int maxNumberOfBackupToKeep) { this.repository = repository; this.backupLocation = backupLocation; this.backupURI = repository.resolveDirectory(repository.createURI(backupLocation), backupName, collection); this.incBackupFiles = new BackupFilePaths(repository, this.backupURI); this.backupName = backupName; this.maxNumberOfBackupToKeep = maxNumberOfBackupToKeep; } @SuppressWarnings("rawtypes") private void backupThenWait() throws SolrServerException, IOException { CollectionAdminRequest.Backup backup = CollectionAdminRequest.backupCollection(getCollectionName(), backupName) .setLocation(backupLocation) .setIncremental(true) .setMaxNumberBackupPoints(maxNumberOfBackupToKeep) .setRepositoryName(BACKUP_REPO_NAME); if (random().nextBoolean()) { try { RequestStatusState state = backup.processAndWait(cluster.getSolrClient(), 1000); assertEquals(RequestStatusState.COMPLETED, state); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("interrupted", e); } numBackup++; } else { CollectionAdminResponse rsp = backup.process(cluster.getSolrClient()); assertEquals(0, rsp.getStatus()); NamedList resp = (NamedList) rsp.getResponse().get("response"); numBackup++; assertEquals(numBackup, resp.get("backupId")); ; } } void incrementalBackupThenVerify() throws IOException, SolrServerException { int numCopiedFiles = copiedFiles().size(); backupThenWait(); List<URI> newFilesCopiedOver = copiedFiles().subList(numCopiedFiles, copiedFiles().size()); verify(newFilesCopiedOver); } ShardBackupMetadata getLastShardBackupId(String shardName) throws IOException { ShardBackupId shardBackupId = BackupProperties.readFromLatest(repository, backupURI) .flatMap(bp -> bp.getShardBackupIdFor(shardName)) .get(); return ShardBackupMetadata.from( repository, new BackupFilePaths(repository, backupURI).getShardBackupMetadataDir(), shardBackupId); } private void assertIndexInputEquals(IndexInput in1, IndexInput in2) throws IOException { assertEquals(in1.length(), in2.length()); for (int i = 0; i < in1.length(); i++) { assertEquals(in1.readByte(), in2.readByte()); } } private void assertFolderAreSame(URI uri1, URI uri2) throws IOException { String[] files1 = repository.listAll(uri1); String[] files2 = repository.listAll(uri2); Arrays.sort(files1); Arrays.sort(files2); assertArrayEquals(files1, files2); for (int i = 0; i < files1.length; i++) { URI file1Uri = repository.resolve(uri1, files1[i]); URI file2Uri = repository.resolve(uri2, files2[i]); assertEquals(repository.getPathType(file1Uri), repository.getPathType(file2Uri)); if (repository.getPathType(file1Uri) == BackupRepository.PathType.DIRECTORY) { assertFolderAreSame(file1Uri, file2Uri); } else { try (IndexInput in1 = repository.openInput(uri1, files1[i], IOContext.READONCE); IndexInput in2 = repository.openInput(uri1, files1[i], IOContext.READONCE)) { assertIndexInputEquals(in1, in2); } } } } public void verify(List<URI> newFilesCopiedOver) throws IOException { // Verify zk files are reuploaded to a appropriate each time a backup is called // TODO make a little change to zk files and make sure that backed up files match with zk data BackupId prevBackupId = new BackupId(Math.max(0, numBackup - 1)); URI backupPropertiesFile = repository.resolve(backupURI, "backup_" + numBackup + ".properties"); URI zkBackupFolder = repository.resolve(backupURI, "zk_backup_" + numBackup); assertTrue(repository.exists(backupPropertiesFile)); assertTrue(repository.exists(zkBackupFolder)); assertFolderAreSame( repository.resolveDirectory(backupURI, BackupFilePaths.getZkStateDir(prevBackupId)), zkBackupFolder); // verify indexes file for (Slice slice : getCollectionState(getCollectionName()).getSlices()) { Replica leader = slice.getLeader(); final ShardBackupMetadata shardBackupMetadata = getLastShardBackupId(slice.getName()); assertNotNull(shardBackupMetadata); try (SolrCore solrCore = cluster.getReplicaJetty(leader).getCoreContainer().getCore(leader.getCoreName())) { Directory dir = solrCore .getDirectoryFactory() .get( solrCore.getIndexDir(), DirectoryFactory.DirContext.DEFAULT, solrCore.getSolrConfig().indexConfig.lockType); try { URI indexDir = incBackupFiles.getIndexDir(); IndexCommit lastCommit = solrCore.getDeletionPolicy().getLatestCommit(); Collection<String> newBackupFiles = newIndexFilesComparedToLastBackup(slice.getName(), lastCommit).stream() .map( indexFile -> { Optional<ShardBackupMetadata.BackedFile> backedFile = shardBackupMetadata.getFile(indexFile); assertTrue(backedFile.isPresent()); return backedFile.get().uniqueFileName; }) .collect(Collectors.toList()); lastCommit .getFileNames() .forEach( f -> { Optional<ShardBackupMetadata.BackedFile> backedFile = shardBackupMetadata.getFile(f); assertTrue(backedFile.isPresent()); String uniqueFileName = backedFile.get().uniqueFileName; if (newBackupFiles.contains(uniqueFileName)) { assertTrue( newFilesCopiedOver.contains( repository.resolve(indexDir, uniqueFileName))); } try { Checksum localChecksum = repository.checksum(dir, f); Checksum remoteChecksum = backedFile.get().fileChecksum; assertEquals(localChecksum.checksum, remoteChecksum.checksum); assertEquals(localChecksum.size, remoteChecksum.size); } catch (IOException e) { throw new AssertionError(e); } }); assertEquals( "Incremental backup stored more files than needed", lastCommit.getFileNames().size(), shardBackupMetadata.listOriginalFileNames().size()); } finally { solrCore.getDirectoryFactory().release(dir); } } } } private Collection<String> newIndexFilesComparedToLastBackup( String shardName, IndexCommit currentCommit) throws IOException { Collection<String> oldFiles = lastShardCommitToBackupFiles.put(shardName, currentCommit.getFileNames()); if (oldFiles == null) oldFiles = new ArrayList<>(); List<String> newFiles = new ArrayList<>(currentCommit.getFileNames()); newFiles.removeAll(oldFiles); return newFiles; } } }
SOLR-16511: Make sure no array/list index can be -1 (#1153)
solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
SOLR-16511: Make sure no array/list index can be -1 (#1153)
<ide><path>olr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java <ide> <ide> protected void corruptIndexFiles() throws IOException { <ide> List<Slice> slices = new ArrayList<>(getCollectionState(getCollectionName()).getSlices()); <del> Replica leader = slices.get(random().nextInt(slices.size()) - 1).getLeader(); <add> Replica leader = slices.get(random().nextInt(slices.size())).getLeader(); <ide> JettySolrRunner leaderNode = cluster.getReplicaJetty(leader); <ide> <ide> final Path fileToCorrupt; <ide> if (indexFiles.isEmpty()) { <ide> return; <ide> } <del> fileToCorrupt = indexFiles.get(random().nextInt(indexFiles.size()) - 1); <add> fileToCorrupt = indexFiles.get(random().nextInt(indexFiles.size())); <ide> } <ide> final byte[] contents = Files.readAllBytes(fileToCorrupt); <ide> for (int i = 1; i < 5; i++) { <ide> int key = contents.length - CodecUtil.footerLength() - i; <del> contents[key] = (byte) (contents[key] + 1); <add> if (key >= 0) { <add> contents[key] = (byte) (contents[key] + 1); <add> } <ide> } <ide> Files.write(fileToCorrupt, contents); <ide> }
Java
apache-2.0
3f438abdd7fcf73d8e66fe58858115ee9e548149
0
maruTA-bis5/mattermost4j,maruTA-bis5/mattermost4j
/* * Copyright (c) 2016-present, Takayuki Maruyama * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package net.bis5.mattermost.model.config; import java.util.List; import lombok.Data; import net.bis5.mattermost.model.config.consts.AllowEditPost; import net.bis5.mattermost.model.config.consts.ConnectionSecurity; import net.bis5.mattermost.model.config.consts.GroupUnreadChannels; import net.bis5.mattermost.model.config.consts.ImageProxyType; import net.bis5.mattermost.model.config.consts.PermissionsDeletePost; import net.bis5.mattermost.model.config.consts.RestrictEmojiCreation; import net.bis5.mattermost.model.config.consts.WebServerMode; /** * Service settings. * * @author Takayuki Maruyama */ @Data public class ServiceSettings { private String siteUrl; private String licenseFileLocation; private String listenAddress; private ConnectionSecurity connectionSecurity; private String tlsCertFile; private String tlsKeyFile; private boolean useLetsEncrypt; private String letsEncryptCertificateCacheFile; private boolean forward80To443; private int readTimeout; private int writeTimeout; private int maximumLoginAttempts; private String googleDeveloperKey; private boolean enableOAuthServiceProvider; private boolean enableIncomingWebhooks; private boolean enableOutgoingWebhooks; private boolean enableCommands; private boolean enableOnlyAdminIntegrations; private boolean enablePostUsernameOverride; private boolean enablePostIconOverride; private boolean enableLinkPreviews; private boolean enableTesting; private boolean enableDeveloper; private boolean enableSecurityFixAlert; private boolean enableInsecureOutgoingConnections; private boolean enableMultifactorAuthentication; private boolean enforceMultifactorAuthentication; private String allowCorsFrom; private int sessionLengthWebInDays; private int sessionLengthMobileInDays; private int sessionLengthSsoInDays; private int sessionCacheInMinutes; private int websocketSecurePort; private int websocketPort; private WebServerMode webServerMode; private boolean enableCustomEmoji; private RestrictEmojiCreation restrictCustomEmojiCreation; private PermissionsDeletePost restrictPostDelete; // XXX really? private AllowEditPost allowEditPost; private int postEditTimeLimit; private long timeBetweenUserTypingUpdatesMilliseconds; private boolean enablePostSearch; private boolean enableUserTypingMessages; private boolean enableUserStatuses; private int clusterLogTimeoutMilliseconds; /* @since Mattermost Server 3.10 */ private int goroutineHealthThreshold; /* @since Mattermost Server 4.0 */ private boolean enableEmojiPicker; /* @since Mattermost Server 4.0 */ private boolean enableChannelViewedMessages; /* @since Mattermost Server 4.0, change default to false in 4.8 */ private boolean enableApiv3 = false; /* @since Mattermost Server 4.1 */ private boolean enableUserAccessTokens; /* @since Mattermost Server 4.2 */ private String allowedUntrustedInternalConnections; /* @since Mattermost Server 4.3 (Enterprise Edition) */ private int sessionIdleTimeoutInMinutes; /* @since Mattermost Server 4.4 */ private boolean closeUnusedDirectMessages; /* @since Mattermost Server 4.5 */ private boolean enablePreviewFeatures = true; /* @since Mattermost Server 4.5 */ private boolean experimentalEnableAuthenticationTransfer = true; /* @since Mattermost Server 4.6 */ private boolean enableTutorial = true; /* @since Mattermost Server 4.7 */ private ImageProxyType imageProxyType; /* @since Mattermost Server 5.10 */ private int minimumHashtagLength = 3; /* @since Mattermost Server 5.10 */ private boolean disableBotsWhenOwnerIsDeactivated = true; /** * Set the image proxy type. * * @deprecated Changed to {@link ImageProxySettings#setImageProxyType(ImageProxyType)} for * Mattermost Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyType(ImageProxyType imageProxyType) { this.imageProxyType = imageProxyType; } /** * Get the image proxy type. * * @deprecated Changed to {@link ImageProxySettings#getImageProxyType()} for Mattermost Server * 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public ImageProxyType getImageProxyType() { return imageProxyType; } /* @since Mattermost Server 4.7 */ private String imageProxyOptions; /** * Set the image proxy options. * * @deprecated Changed to {@link ImageProxySettings#setRemoteImageProxyOptions(String)} for * Mattermost Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyOptions(String imageProxyOptions) { this.imageProxyOptions = imageProxyOptions; } /** * Get the image proxy options. * * @deprecated Changed to {@link ImageProxySettings#getRemoteImageProxyOptions()} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public String getImageProxyOptions() { return imageProxyOptions; } /* @since Mattermost Server 4.7 */ private String imageProxyUrl; /** * Set the image proxy url. * * @deprecated Changed to {@link ImageProxySettings#setRemoteImageProxyUrl(String)} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyUrl(String imageProxyUrl) { this.imageProxyUrl = imageProxyUrl; } /** * Get the image proxy url. * * @deprecated Changed to {@link ImageProxySettings#getRemoteImageProxyUrl()} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public String getImageProxyUrl() { return imageProxyUrl; } /* @since Mattermost Server 4.7 */ private GroupUnreadChannels experimentalGroupUnreadChannels = GroupUnreadChannels.DISABLED; /* @since Mattermost Server 4.7 */ private boolean experimentalEnableDefaultChannelLeaveJoinMessages = true; /* @since Mattermost 4.8 */ private boolean allowCookiesForSubdomains; /* @since Mattermost 4.8 */ private String websocketUrl; /* @since Mattermost Server XXX what ver? */ private boolean enableEmailInvitations; /* @since Mattermost Server 5.0 */ private boolean enableApiTeamDeletion; /* @since Mattermost Server 5.0 */ private boolean experimentalEnableHardenedMode; /* @since Mattermost Server 5.1 */ private boolean enableGifPicker; /* @since Mattermpst Server 5.1 */ private String gfycatApiKey; /* @since Mattermost Server 5.1 */ private String gfycatApiSecret; /* @since Mattermost Server 5.1 */ private boolean experimentalLimitClientConfig; /* @since Mattermost Server 5.2 */ private String corsExposedHeaders; /* @since Mattermost Server 5.2 */ private boolean corsAllowCredentials; /* @since Mattermost Server 5.2 */ private boolean corsDebug; /* @since Mattermost Server 5.2 */ private boolean experimentalChannelOrganization; /* @since Mattermost Server 5.6 */ private String tlsMinVer; /* @since Mattermost Server 5.6 */ private boolean tlsStrictTransport; /* @since Mattermost Server 5.6 */ private long tlsStrictTransportMaxAge; /* @since Mattermost Server 5.6 */ private List<String> tlsOverwriteCiphers; /* @since Mattermost Server 5.8 */ private boolean experimentalLdapGroupSync; /* @since Mattermost Server 5.8 */ private boolean experimentalStrictCsrfEnforcement; /* @since Mattermost Server 5.9 */ private boolean disableLegacyMfa; /** * This method should not use. * * @deprecated This is typo. Please use {@link #getGoroutineHealthThreshold()} */ @Deprecated public int getGoroutineHealthThreshould() { return getGoroutineHealthThreshold(); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #setGoroutineHealthThreshold(int)} */ @Deprecated public void setGoroutineHealthThreshould(int goroutineHealthThresould) { setGoroutineHealthThreshold(goroutineHealthThresould); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #isEnableUserAccessTokens()} */ @Deprecated public boolean isEnableUserAccessToken() { return isEnableUserAccessTokens(); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #setEnableUserAccessToken(boolean)} */ @Deprecated public void setEnableUserAccessToken(boolean enableUserAccessToken) { setEnableUserAccessTokens(enableUserAccessToken); } }
mattermost-models/src/main/java/net/bis5/mattermost/model/config/ServiceSettings.java
/* * Copyright (c) 2016-present, Takayuki Maruyama * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package net.bis5.mattermost.model.config; import java.util.List; import lombok.Data; import net.bis5.mattermost.model.config.consts.AllowEditPost; import net.bis5.mattermost.model.config.consts.ConnectionSecurity; import net.bis5.mattermost.model.config.consts.GroupUnreadChannels; import net.bis5.mattermost.model.config.consts.ImageProxyType; import net.bis5.mattermost.model.config.consts.PermissionsDeletePost; import net.bis5.mattermost.model.config.consts.RestrictEmojiCreation; import net.bis5.mattermost.model.config.consts.WebServerMode; /** * Service settings. * * @author Takayuki Maruyama */ @Data public class ServiceSettings { private String siteUrl; private String licenseFileLocation; private String listenAddress; private ConnectionSecurity connectionSecurity; private String tlsCertFile; private String tlsKeyFile; private boolean useLetsEncrypt; private String letsEncryptCertificateCacheFile; private boolean forward80To443; private int readTimeout; private int writeTimeout; private int maximumLoginAttempts; private String googleDeveloperKey; private boolean enableOAuthServiceProvider; private boolean enableIncomingWebhooks; private boolean enableOutgoingWebhooks; private boolean enableCommands; private boolean enableOnlyAdminIntegrations; private boolean enablePostUsernameOverride; private boolean enablePostIconOverride; private boolean enableLinkPreviews; private boolean enableTesting; private boolean enableDeveloper; private boolean enableSecurityFixAlert; private boolean enableInsecureOutgoingConnections; private boolean enableMultifactorAuthentication; private boolean enforceMultifactorAuthentication; private String allowCorsFrom; private int sessionLengthWebInDays; private int sessionLengthMobileInDays; private int sessionLengthSsoInDays; private int sessionCacheInMinutes; private int websocketSecurePort; private int websocketPort; private WebServerMode webServerMode; private boolean enableCustomEmoji; private RestrictEmojiCreation restrictCustomEmojiCreation; private PermissionsDeletePost restrictPostDelete; // XXX really? private AllowEditPost allowEditPost; private int postEditTimeLimit; private long timeBetweenUserTypingUpdatesMilliseconds; private boolean enablePostSearch; private boolean enableUserTypingMessages; private boolean enableUserStatuses; private int clusterLogTimeoutMilliseconds; /* @since Mattermost Server 3.10 */ private int goroutineHealthThreshold; /* @since Mattermost Server 4.0 */ private boolean enableEmojiPicker; /* @since Mattermost Server 4.0 */ private boolean enableChannelViewedMessages; /* @since Mattermost Server 4.0, change default to false in 4.8 */ private boolean enableApiv3 = false; /* @since Mattermost Server 4.1 */ private boolean enableUserAccessTokens; /* @since Mattermost Server 4.2 */ private String allowedUntrustedInternalConnections; /* @since Mattermost Server 4.3 (Enterprise Edition) */ private int sessionIdleTimeoutInMinutes; /* @since Mattermost Server 4.4 */ private boolean closeUnusedDirectMessages; /* @since Mattermost Server 4.5 */ private boolean enablePreviewFeatures = true; /* @since Mattermost Server 4.5 */ private boolean experimentalEnableAuthenticationTransfer = true; /* @since Mattermost Server 4.6 */ private boolean enableTutorial = true; /* @since Mattermost Server 4.7 */ private ImageProxyType imageProxyType; /* @since Mattermost Server 5.10 */ private int minimumHashtagLength = 3; /* @since Mattermost Server 5.10 */ private boolean disableBotsWhenOwnerIsDeactivated = true; /** * Set the image proxy type. * * @Deprecated Changed to {@link ImageProxySettings#setImageProxyType(ImageProxyType)} for * Mattermost Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyType(ImageProxyType imageProxyType) { this.imageProxyType = imageProxyType; } /** * Get the image proxy type. * * @Deprecated Changed to {@link ImageProxySettings#getImageProxyType()} for Mattermost Server * 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public ImageProxyType getImageProxyType() { return imageProxyType; } /* @since Mattermost Server 4.7 */ private String imageProxyOptions; /** * Set the image proxy options. * * @deprecated Changed to {@link ImageProxySettings#setRemoteImageProxyOptions(String)} for * Mattermost Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyOptions(String imageProxyOptions) { this.imageProxyOptions = imageProxyOptions; } /** * Get the image proxy options. * * @deprecated Changed to {@link ImageProxySettings#getRemoteImageProxyOptions()} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public String getImageProxyOptions() { return imageProxyOptions; } /* @since Mattermost Server 4.7 */ private String imageProxyUrl; /** * Set the image proxy url. * * @deprecated Changed to {@link ImageProxySettings#setRemoteImageProxyUrl(String)} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public void setImageProxyUrl(String imageProxyUrl) { this.imageProxyUrl = imageProxyUrl; } /** * Get the image proxy url. * * @deprecated Changed to {@link ImageProxySettings#getRemoteImageProxyUrl()} for Mattermost * Server 5.8+ * @since Mattermost Server 4.7 */ @Deprecated public String getImageProxyUrl() { return imageProxyUrl; } /* @since Mattermost Server 4.7 */ private GroupUnreadChannels experimentalGroupUnreadChannels = GroupUnreadChannels.DISABLED; /* @since Mattermost Server 4.7 */ private boolean experimentalEnableDefaultChannelLeaveJoinMessages = true; /* @since Mattermost 4.8 */ private boolean allowCookiesForSubdomains; /* @since Mattermost 4.8 */ private String websocketUrl; /* @since Mattermost Server XXX what ver? */ private boolean enableEmailInvitations; /* @since Mattermost Server 5.0 */ private boolean enableApiTeamDeletion; /* @since Mattermost Server 5.0 */ private boolean experimentalEnableHardenedMode; /* @since Mattermost Server 5.1 */ private boolean enableGifPicker; /* @since Mattermpst Server 5.1 */ private String gfycatApiKey; /* @since Mattermost Server 5.1 */ private String gfycatApiSecret; /* @since Mattermost Server 5.1 */ private boolean experimentalLimitClientConfig; /* @since Mattermost Server 5.2 */ private String corsExposedHeaders; /* @since Mattermost Server 5.2 */ private boolean corsAllowCredentials; /* @since Mattermost Server 5.2 */ private boolean corsDebug; /* @since Mattermost Server 5.2 */ private boolean experimentalChannelOrganization; /* @since Mattermost Server 5.6 */ private String tlsMinVer; /* @since Mattermost Server 5.6 */ private boolean tlsStrictTransport; /* @since Mattermost Server 5.6 */ private long tlsStrictTransportMaxAge; /* @since Mattermost Server 5.6 */ private List<String> tlsOverwriteCiphers; /* @since Mattermost Server 5.8 */ private boolean experimentalLdapGroupSync; /* @since Mattermost Server 5.8 */ private boolean experimentalStrictCsrfEnforcement; /* @since Mattermost Server 5.9 */ private boolean disableLegacyMfa; /** * This method should not use. * * @deprecated This is typo. Please use {@link #getGoroutineHealthThreshold()} */ @Deprecated public int getGoroutineHealthThreshould() { return getGoroutineHealthThreshold(); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #setGoroutineHealthThreshold(int)} */ @Deprecated public void setGoroutineHealthThreshould(int goroutineHealthThresould) { setGoroutineHealthThreshold(goroutineHealthThresould); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #isEnableUserAccessTokens()} */ @Deprecated public boolean isEnableUserAccessToken() { return isEnableUserAccessTokens(); } /** * This method should not use. * * @deprecated This is typo. Please use {@link #setEnableUserAccessToken(boolean)} */ @Deprecated public void setEnableUserAccessToken(boolean enableUserAccessToken) { setEnableUserAccessTokens(enableUserAccessToken); } }
Fix javadoc tag typo (#215)
mattermost-models/src/main/java/net/bis5/mattermost/model/config/ServiceSettings.java
Fix javadoc tag typo (#215)
<ide><path>attermost-models/src/main/java/net/bis5/mattermost/model/config/ServiceSettings.java <ide> /** <ide> * Set the image proxy type. <ide> * <del> * @Deprecated Changed to {@link ImageProxySettings#setImageProxyType(ImageProxyType)} for <add> * @deprecated Changed to {@link ImageProxySettings#setImageProxyType(ImageProxyType)} for <ide> * Mattermost Server 5.8+ <ide> * @since Mattermost Server 4.7 <ide> */ <ide> /** <ide> * Get the image proxy type. <ide> * <del> * @Deprecated Changed to {@link ImageProxySettings#getImageProxyType()} for Mattermost Server <add> * @deprecated Changed to {@link ImageProxySettings#getImageProxyType()} for Mattermost Server <ide> * 5.8+ <ide> * @since Mattermost Server 4.7 <ide> */
Java
apache-2.0
498d252e682fad2efb6f166af35111956456fbe2
0
gilesp/taskhelper,gilesp/taskhelper,gilesp/taskhelper
package uk.co.vurt.hakken.fragments; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; //TODO Kash & Martina convert the TaskList activity to this fragment. See JobList and //JobListFragment for an example of how this is done. public class TaskDefinitionsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { // TODO Auto-generated method stub return null; } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) { // TODO Auto-generated method stub } @Override public void onLoaderReset(Loader<Cursor> arg0) { // TODO Auto-generated method stub } }
hakken-android-client/src/main/java/uk/co/vurt/hakken/fragments/TaskDefinitionsListFragment.java
package uk.co.vurt.hakken.fragments; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; public class TaskDefinitionsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { // TODO Auto-generated method stub return null; } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) { // TODO Auto-generated method stub } @Override public void onLoaderReset(Loader<Cursor> arg0) { // TODO Auto-generated method stub } }
Added todo comment
hakken-android-client/src/main/java/uk/co/vurt/hakken/fragments/TaskDefinitionsListFragment.java
Added todo comment
<ide><path>akken-android-client/src/main/java/uk/co/vurt/hakken/fragments/TaskDefinitionsListFragment.java <ide> import android.support.v4.app.ListFragment; <ide> import android.support.v4.app.LoaderManager; <ide> import android.support.v4.content.Loader; <del> <add>//TODO Kash & Martina convert the TaskList activity to this fragment. See JobList and <add>//JobListFragment for an example of how this is done. <ide> public class TaskDefinitionsListFragment extends ListFragment implements <ide> LoaderManager.LoaderCallbacks<Cursor> { <ide>
Java
mit
4677b985a415e1466f6b92f852e2017c27167f18
0
InfinityPhase/CARIS,InfinityPhase/CARIS
package responders; import library.Constants; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import tokens.Response; public class MentionResponder extends Responder { // Placeholder example auto handler @Override public Response process(MessageReceivedEvent event) { setup(event); if( containsIgnoreCase(messageText, " " + Constants.NAME + " ") ) { response = "What is it?"; if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder triggered.");} } else if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder unactivated.");} if( Constants.DEBUG ) {System.out.println("\t\t\tMentionResponder processed.");} return build(); } }
src/responders/MentionResponder.java
package responders; import library.Constants; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import tokens.Response; public class MentionResponder extends Responder { // Placeholder example auto handler @Override public Response process(MessageReceivedEvent event) { setup(event); if( containsIgnoreCase(tokens, Constants.NAME) ) { response = "What is it?"; if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder triggered.");} } else if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder unactivated.");} if( Constants.DEBUG ) {System.out.println("\t\t\tMentionResponder processed.");} return build(); } }
Fixed mentioning
src/responders/MentionResponder.java
Fixed mentioning
<ide><path>rc/responders/MentionResponder.java <ide> public Response process(MessageReceivedEvent event) { <ide> setup(event); <ide> <del> if( containsIgnoreCase(tokens, Constants.NAME) ) { <add> if( containsIgnoreCase(messageText, " " + Constants.NAME + " ") ) { <ide> response = "What is it?"; <ide> if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder triggered.");} <ide> } else if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder unactivated.");}
Java
apache-2.0
123daaca0d700b386c344e4fe8a628beea10f96e
0
dain/presto,ebyhr/presto,Praveen2112/presto,dain/presto,dain/presto,Praveen2112/presto,ebyhr/presto,ebyhr/presto,ebyhr/presto,smartnews/presto,Praveen2112/presto,smartnews/presto,Praveen2112/presto,dain/presto,smartnews/presto,Praveen2112/presto,dain/presto,smartnews/presto,smartnews/presto,ebyhr/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.hive; import com.google.common.collect.ImmutableMap; import io.airlift.units.Duration; import io.trino.Session; import io.trino.testing.AbstractTestQueryFramework; import io.trino.testing.MaterializedResult; import io.trino.testing.QueryRunner; import org.intellij.lang.annotations.Language; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static io.trino.testing.QueryAssertions.assertEqualsIgnoreOrder; import static io.trino.testing.sql.TestTable.randomTableSuffix; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; public class TestParquetPageSkipping extends AbstractTestQueryFramework { @Override protected QueryRunner createQueryRunner() throws Exception { return HiveQueryRunner.builder() .setHiveProperties(ImmutableMap.of( // Reduce writer sort buffer size to ensure SortingFileWriter gets used "hive.writer-sort-buffer-size", "1MB", "parquet.use-column-index", "true")) .build(); } private void buildSortedTables(String tableName, String sortByColumnName, String sortByColumnType) { String createTableTemplate = "CREATE TABLE %s ( " + " orderkey bigint, " + " custkey bigint, " + " orderstatus varchar(1), " + " totalprice double, " + " orderdate date, " + " orderpriority varchar(15), " + " clerk varchar(15), " + " shippriority integer, " + " comment varchar(79), " + " rvalues double array " + ") " + "WITH ( " + " format = 'PARQUET', " + " bucketed_by = array['orderstatus'], " + " bucket_count = 1, " + " sorted_by = array['%s'] " + ")"; createTableTemplate = createTableTemplate.replaceFirst(sortByColumnName + "[ ]+([^,]*)", sortByColumnName + " " + sortByColumnType); assertUpdate(format( createTableTemplate, tableName, sortByColumnName)); String catalog = getSession().getCatalog().orElseThrow(); assertUpdate( Session.builder(getSession()) .setCatalogSessionProperty(catalog, "parquet_writer_page_size", "10000B") .setCatalogSessionProperty(catalog, "parquet_writer_block_size", "100GB") .build(), format("INSERT INTO %s SELECT *, ARRAY[rand(), rand(), rand()] FROM tpch.tiny.orders", tableName), 15000); } @Test public void testAndPredicates() { String tableName = "test_and_predicate_" + randomTableSuffix(); buildSortedTables(tableName, "totalprice", "double"); int rowCount = assertColumnIndexResults("SELECT * FROM " + tableName + " WHERE totalprice BETWEEN 100000 AND 131280 AND clerk = 'Clerk#000000624'"); assertThat(rowCount).isGreaterThan(0); // `totalprice BETWEEN 51890 AND 51900` is chosen to lie between min/max values of row group // but outside page level min/max boundaries to trigger pruning of row group using column index assertRowGroupPruning("SELECT * FROM " + tableName + " WHERE totalprice BETWEEN 51890 AND 51900 AND orderkey > 0"); assertUpdate("DROP TABLE " + tableName); } @Test(dataProvider = "dataType") public void testPageSkipping(String sortByColumn, String sortByColumnType, Object[][] valuesArray) { String tableName = "test_page_skipping_" + randomTableSuffix(); buildSortedTables(tableName, sortByColumn, sortByColumnType); for (Object[] values : valuesArray) { Object lowValue = values[0]; Object middleLowValue = values[1]; Object middleHighValue = values[2]; Object highValue = values[3]; assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s = %s", sortByColumn, tableName, sortByColumn, middleLowValue)); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s < %s ORDER BY %s", sortByColumn, tableName, sortByColumn, lowValue, sortByColumn))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s > %s ORDER BY %s", sortByColumn, tableName, sortByColumn, highValue, sortByColumn))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s BETWEEN %s AND %s ORDER BY %s", sortByColumn, tableName, sortByColumn, middleLowValue, middleHighValue, sortByColumn))).isGreaterThan(0); // Tests synchronization of reading values across columns assertColumnIndexResults(format("SELECT * FROM %s WHERE %s = %s ORDER BY orderkey", tableName, sortByColumn, middleLowValue)); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s < %s ORDER BY orderkey", tableName, sortByColumn, lowValue))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s > %s ORDER BY orderkey", tableName, sortByColumn, highValue))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s BETWEEN %s AND %s ORDER BY orderkey", tableName, sortByColumn, middleLowValue, middleHighValue))).isGreaterThan(0); } assertUpdate("DROP TABLE " + tableName); } private int assertColumnIndexResults(String query) { MaterializedResult withColumnIndexing = computeActual(query); MaterializedResult withoutColumnIndexing = computeActual(noParquetColumnIndexFiltering(getSession()), query); assertEqualsIgnoreOrder(withColumnIndexing, withoutColumnIndexing); return withoutColumnIndexing.getRowCount(); } private void assertRowGroupPruning(@Language("SQL") String sql) { assertQueryStats( noParquetColumnIndexFiltering(getSession()), sql, queryStats -> { assertThat(queryStats.getPhysicalInputPositions()).isGreaterThan(0); assertThat(queryStats.getProcessedInputPositions()).isEqualTo(queryStats.getPhysicalInputPositions()); }, results -> assertThat(results.getRowCount()).isEqualTo(0), new Duration(10, SECONDS)); assertQueryStats( getSession(), sql, queryStats -> { assertThat(queryStats.getPhysicalInputPositions()).isEqualTo(0); assertThat(queryStats.getProcessedInputPositions()).isEqualTo(0); }, results -> assertThat(results.getRowCount()).isEqualTo(0), new Duration(10, SECONDS)); } @DataProvider public Object[][] dataType() { return new Object[][] { {"orderkey", "bigint", new Object[][] {{2, 7520, 7523, 14950}}}, {"totalprice", "double", new Object[][] {{974.04, 131094.34, 131279.97, 406938.36}}}, {"totalprice", "real", new Object[][] {{974.04, 131094.34, 131279.97, 406938.36}}}, {"totalprice", "decimal(12,2)", new Object[][] { {974.04, 131094.34, 131279.97, 406938.36}, {973, 131095, 131280, 406950}, {974.04123, 131094.34123, 131279.97012, 406938.36555}}}, {"totalprice", "decimal(12,0)", new Object[][] { {973, 131095, 131280, 406950}}}, {"totalprice", "decimal(35,2)", new Object[][] { {974.04, 131094.34, 131279.97, 406938.36}, {973, 131095, 131280, 406950}, {974.04123, 131094.34123, 131279.97012, 406938.36555}}}, {"orderdate", "date", new Object[][] {{"DATE '1992-01-05'", "DATE '1995-10-13'", "DATE '1995-10-13'", "DATE '1998-07-29'"}}}, {"orderdate", "timestamp", new Object[][] {{"TIMESTAMP '1992-01-05'", "TIMESTAMP '1995-10-13'", "TIMESTAMP '1995-10-14'", "TIMESTAMP '1998-07-29'"}}}, {"clerk", "varchar(15)", new Object[][] {{"'Clerk#000000006'", "'Clerk#000000508'", "'Clerk#000000513'", "'Clerk#000000996'"}}}, {"custkey", "integer", new Object[][] {{4, 634, 640, 1493}}}, {"custkey", "smallint", new Object[][] {{4, 634, 640, 1493}}} }; } private Session noParquetColumnIndexFiltering(Session session) { return Session.builder(session) .setCatalogSessionProperty(session.getCatalog().orElseThrow(), "parquet_use_column_index", "false") .build(); } }
plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestParquetPageSkipping.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.hive; import com.google.common.collect.ImmutableMap; import io.airlift.units.Duration; import io.trino.Session; import io.trino.testing.AbstractTestQueryFramework; import io.trino.testing.MaterializedResult; import io.trino.testing.QueryRunner; import org.intellij.lang.annotations.Language; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static io.trino.testing.assertions.Assert.assertEquals; import static io.trino.testing.sql.TestTable.randomTableSuffix; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; public class TestParquetPageSkipping extends AbstractTestQueryFramework { @Override protected QueryRunner createQueryRunner() throws Exception { return HiveQueryRunner.builder() .setHiveProperties(ImmutableMap.of( // Reduce writer sort buffer size to ensure SortingFileWriter gets used "hive.writer-sort-buffer-size", "1MB", "parquet.use-column-index", "true")) .build(); } private void buildSortedTables(String tableName, String sortByColumnName, String sortByColumnType) { String createTableTemplate = "CREATE TABLE %s ( " + " orderkey bigint, " + " custkey bigint, " + " orderstatus varchar(1), " + " totalprice double, " + " orderdate date, " + " orderpriority varchar(15), " + " clerk varchar(15), " + " shippriority integer, " + " comment varchar(79), " + " rvalues double array " + ") " + "WITH ( " + " format = 'PARQUET', " + " bucketed_by = array['orderstatus'], " + " bucket_count = 1, " + " sorted_by = array['%s'] " + ")"; createTableTemplate = createTableTemplate.replaceFirst(sortByColumnName + "[ ]+([^,]*)", sortByColumnName + " " + sortByColumnType); assertUpdate(format( createTableTemplate, tableName, sortByColumnName)); String catalog = getSession().getCatalog().orElseThrow(); assertUpdate( Session.builder(getSession()) .setCatalogSessionProperty(catalog, "parquet_writer_page_size", "10000B") .setCatalogSessionProperty(catalog, "parquet_writer_block_size", "100GB") .build(), format("INSERT INTO %s SELECT *, ARRAY[rand(), rand(), rand()] FROM tpch.tiny.orders", tableName), 15000); } @Test public void testAndPredicates() { String tableName = "test_and_predicate_" + randomTableSuffix(); buildSortedTables(tableName, "totalprice", "double"); int rowCount = assertColumnIndexResults("SELECT * FROM " + tableName + " WHERE totalprice BETWEEN 100000 AND 131280 AND clerk = 'Clerk#000000624'"); assertThat(rowCount).isGreaterThan(0); // `totalprice BETWEEN 51890 AND 51900` is chosen to lie between min/max values of row group // but outside page level min/max boundaries to trigger pruning of row group using column index assertRowGroupPruning("SELECT * FROM " + tableName + " WHERE totalprice BETWEEN 51890 AND 51900 AND orderkey > 0"); assertUpdate("DROP TABLE " + tableName); } @Test(dataProvider = "dataType") public void testPageSkipping(String sortByColumn, String sortByColumnType, Object[][] valuesArray) { String tableName = "test_page_skipping_" + randomTableSuffix(); buildSortedTables(tableName, sortByColumn, sortByColumnType); for (Object[] values : valuesArray) { Object lowValue = values[0]; Object middleLowValue = values[1]; Object middleHighValue = values[2]; Object highValue = values[3]; assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s = %s", sortByColumn, tableName, sortByColumn, middleLowValue)); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s < %s ORDER BY %s", sortByColumn, tableName, sortByColumn, lowValue, sortByColumn))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s > %s ORDER BY %s", sortByColumn, tableName, sortByColumn, highValue, sortByColumn))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT %s FROM %s WHERE %s BETWEEN %s AND %s ORDER BY %s", sortByColumn, tableName, sortByColumn, middleLowValue, middleHighValue, sortByColumn))).isGreaterThan(0); // Tests synchronization of reading values across columns assertColumnIndexResults(format("SELECT * FROM %s WHERE %s = %s ORDER BY orderkey", tableName, sortByColumn, middleLowValue)); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s < %s ORDER BY orderkey", tableName, sortByColumn, lowValue))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s > %s ORDER BY orderkey", tableName, sortByColumn, highValue))).isGreaterThan(0); assertThat(assertColumnIndexResults(format("SELECT * FROM %s WHERE %s BETWEEN %s AND %s ORDER BY orderkey", tableName, sortByColumn, middleLowValue, middleHighValue))).isGreaterThan(0); } assertUpdate("DROP TABLE " + tableName); } private int assertColumnIndexResults(String query) { MaterializedResult withColumnIndexing = computeActual(query); MaterializedResult withoutColumnIndexing = computeActual(noParquetColumnIndexFiltering(getSession()), query); assertEquals(withColumnIndexing, withoutColumnIndexing); return withoutColumnIndexing.getRowCount(); } private void assertRowGroupPruning(@Language("SQL") String sql) { assertQueryStats( noParquetColumnIndexFiltering(getSession()), sql, queryStats -> { assertThat(queryStats.getPhysicalInputPositions()).isGreaterThan(0); assertThat(queryStats.getProcessedInputPositions()).isEqualTo(queryStats.getPhysicalInputPositions()); }, results -> assertThat(results.getRowCount()).isEqualTo(0), new Duration(10, SECONDS)); assertQueryStats( getSession(), sql, queryStats -> { assertThat(queryStats.getPhysicalInputPositions()).isEqualTo(0); assertThat(queryStats.getProcessedInputPositions()).isEqualTo(0); }, results -> assertThat(results.getRowCount()).isEqualTo(0), new Duration(10, SECONDS)); } @DataProvider public Object[][] dataType() { return new Object[][] { {"orderkey", "bigint", new Object[][] {{2, 7520, 7523, 14950}}}, {"totalprice", "double", new Object[][] {{974.04, 131094.34, 131279.97, 406938.36}}}, {"totalprice", "real", new Object[][] {{974.04, 131094.34, 131279.97, 406938.36}}}, {"totalprice", "decimal(12,2)", new Object[][] { {974.04, 131094.34, 131279.97, 406938.36}, {973, 131095, 131280, 406950}, {974.04123, 131094.34123, 131279.97012, 406938.36555}}}, {"totalprice", "decimal(12,0)", new Object[][] { {973, 131095, 131280, 406950}}}, {"totalprice", "decimal(35,2)", new Object[][] { {974.04, 131094.34, 131279.97, 406938.36}, {973, 131095, 131280, 406950}, {974.04123, 131094.34123, 131279.97012, 406938.36555}}}, {"orderdate", "date", new Object[][] {{"DATE '1992-01-05'", "DATE '1995-10-13'", "DATE '1995-10-13'", "DATE '1998-07-29'"}}}, {"orderdate", "timestamp", new Object[][] {{"TIMESTAMP '1992-01-05'", "TIMESTAMP '1995-10-13'", "TIMESTAMP '1995-10-14'", "TIMESTAMP '1998-07-29'"}}}, {"clerk", "varchar(15)", new Object[][] {{"'Clerk#000000006'", "'Clerk#000000508'", "'Clerk#000000513'", "'Clerk#000000996'"}}}, {"custkey", "integer", new Object[][] {{4, 634, 640, 1493}}}, {"custkey", "smallint", new Object[][] {{4, 634, 640, 1493}}} }; } private Session noParquetColumnIndexFiltering(Session session) { return Session.builder(session) .setCatalogSessionProperty(session.getCatalog().orElseThrow(), "parquet_use_column_index", "false") .build(); } }
Use assertEqualsIgnoreOrder in assertColumnIndexResults
plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestParquetPageSkipping.java
Use assertEqualsIgnoreOrder in assertColumnIndexResults
<ide><path>lugin/trino-hive/src/test/java/io/trino/plugin/hive/TestParquetPageSkipping.java <ide> import org.testng.annotations.DataProvider; <ide> import org.testng.annotations.Test; <ide> <del>import static io.trino.testing.assertions.Assert.assertEquals; <add>import static io.trino.testing.QueryAssertions.assertEqualsIgnoreOrder; <ide> import static io.trino.testing.sql.TestTable.randomTableSuffix; <ide> import static java.lang.String.format; <ide> import static java.util.concurrent.TimeUnit.SECONDS; <ide> { <ide> MaterializedResult withColumnIndexing = computeActual(query); <ide> MaterializedResult withoutColumnIndexing = computeActual(noParquetColumnIndexFiltering(getSession()), query); <del> assertEquals(withColumnIndexing, withoutColumnIndexing); <add> assertEqualsIgnoreOrder(withColumnIndexing, withoutColumnIndexing); <ide> return withoutColumnIndexing.getRowCount(); <ide> } <ide>
Java
apache-2.0
bb1a8ee27be8202c7d19d09e4b34219c80e97f30
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.axis2; import org.apache.axiom.om.util.UUIDGenerator; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingHelper; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.TransportInDescription; import org.apache.axis2.description.TransportOutDescription; import org.apache.axis2.engine.AxisEngine; import org.apache.axis2.engine.DependencyManager; import org.apache.axis2.engine.Handler.InvocationResponse; import org.apache.axis2.jaxws.description.builder.WsdlComposite; import org.apache.axis2.jaxws.description.builder.WsdlGenerator; import org.apache.axis2.jaxws.server.JAXWSMessageReceiver; import org.apache.axis2.transport.OutTransportInfo; import org.apache.axis2.transport.RequestResponseTransport; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.transport.http.HTTPTransportReceiver; import org.apache.axis2.transport.http.HTTPTransportUtils; import org.apache.axis2.transport.http.util.RESTUtil; import org.apache.axis2.util.MessageContextBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.jaxws.JAXWSUtils; import org.apache.geronimo.jaxws.JNDIResolver; import org.apache.geronimo.jaxws.PortInfo; import org.apache.geronimo.jaxws.ServerJNDIResolver; import org.apache.geronimo.webservices.WebServiceContainer; import org.apache.geronimo.webservices.saaj.SAAJUniverse; import org.apache.ws.commons.schema.XmlSchema; import javax.naming.Context; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.wsdl.Definition; import javax.wsdl.Service; import javax.wsdl.Port; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.soap.SOAPAddress; import javax.wsdl.extensions.soap12.SOAP12Address; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLWriter; import javax.xml.namespace.QName; import javax.xml.ws.WebServiceException; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URL; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.List; import java.util.concurrent.CountDownLatch; /** * @version $Rev$ $Date$ */ public abstract class Axis2WebServiceContainer implements WebServiceContainer { private static final Log log = LogFactory.getLog(Axis2WebServiceContainer.class); public static final String REQUEST = Axis2WebServiceContainer.class.getName() + "@Request"; public static final String RESPONSE = Axis2WebServiceContainer.class.getName() + "@Response"; private transient final ClassLoader classLoader; private final String endpointClassName; protected org.apache.geronimo.jaxws.PortInfo portInfo; protected ConfigurationContext configurationContext; private JNDIResolver jndiResolver; private AxisService service; private URL configurationBaseUrl; public Axis2WebServiceContainer(PortInfo portInfo, String endpointClassName, ClassLoader classLoader, Context context, URL configurationBaseUrl) { this.classLoader = classLoader; this.endpointClassName = endpointClassName; this.portInfo = portInfo; this.configurationBaseUrl = configurationBaseUrl; try { configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext(); //check to see if the wsdlLocation property is set in portInfo, //if not checking if wsdlLocation exists in annotation //if already set, annotation should not overwrite it. if (portInfo.getWsdlFile() == null || portInfo.getWsdlFile().equals("")){ Class clazz = classLoader.loadClass(endpointClassName); //getwsdllocation from annotation if it exists if (JAXWSUtils.containsWsdlLocation(clazz, classLoader)) portInfo.setWsdlFile(JAXWSUtils.getServiceWsdlLocation(clazz, classLoader)); } if(portInfo.getWsdlFile() != null && !portInfo.getWsdlFile().equals("")){ //WSDL file Has been provided AxisServiceGenerator serviceGen = new AxisServiceGenerator(); service = serviceGen.getServiceFromWSDL(portInfo, endpointClassName, configurationBaseUrl, classLoader); }else { //No WSDL, Axis2 will handle it. Is it ? service = AxisService.createService(endpointClassName, configurationContext.getAxisConfiguration(), JAXWSMessageReceiver.class); } service.setScope(Constants.SCOPE_APPLICATION); configurationContext.getAxisConfiguration().addService(service); } catch (AxisFault af) { throw new RuntimeException(af); } catch (Exception e) { throw new RuntimeException(e); } jndiResolver = new ServerJNDIResolver(context); } public void getWsdl(Request request, Response response) throws Exception { doService(request, response); } public void invoke(Request request, Response response) throws Exception { SAAJUniverse universe = new SAAJUniverse(); universe.set(SAAJUniverse.AXIS2); try { doService(request, response); } finally { universe.unset(); } } protected void doService(final Request request, final Response response) throws Exception { initContextRoot(request); if (log.isDebugEnabled()) { log.debug("Target URI: " + request.getURI()); } MessageContext msgContext = new MessageContext(); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP); msgContext.setProperty(MessageContext.REMOTE_ADDR, request.getRemoteAddr()); try { TransportOutDescription transportOut = this.configurationContext.getAxisConfiguration() .getTransportOut(Constants.TRANSPORT_HTTP); TransportInDescription transportIn = this.configurationContext.getAxisConfiguration() .getTransportIn(Constants.TRANSPORT_HTTP); msgContext.setConfigurationContext(this.configurationContext); //TODO: Port this segment for session support. // String sessionKey = (String) this.httpcontext.getAttribute(HTTPConstants.COOKIE_STRING); // if (this.configurationContext.getAxisConfiguration().isManageTransportSession()) { // SessionContext sessionContext = this.sessionManager.getSessionContext(sessionKey); // msgContext.setSessionContext(sessionContext); // } msgContext.setTransportIn(transportIn); msgContext.setTransportOut(transportOut); msgContext.setServiceGroupContextId(UUIDGenerator.getUUID()); msgContext.setServerSide(true); // // set the transport Headers // HashMap headerMap = new HashMap(); // for (Iterator it = request.headerIterator(); it.hasNext();) { // Header header = (Header) it.next(); // headerMap.put(header.getName(), header.getValue()); // } // msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); // // this.httpcontext.setAttribute(AxisParams.MESSAGE_CONTEXT, msgContext); doService2(request, response, msgContext); } catch (Throwable e) { try { AxisEngine engine = new AxisEngine(this.configurationContext); msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e); // If the fault is not going along the back channel we should be 202ing if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatusCode(202); } else { response.setStatusCode(500); response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/plain"); PrintWriter pw = new PrintWriter(response.getOutputStream()); e.printStackTrace(pw); pw.flush(); String msg = "Exception occurred while trying to invoke service method doService()"; log.error(msg, e); } engine.sendFault(faultContext); } catch (Exception ex) { if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatusCode(202); } else { response.setStatusCode(500); response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/plain"); PrintWriter pw = new PrintWriter(response.getOutputStream()); ex.printStackTrace(pw); pw.flush(); String msg = "Exception occurred while trying to invoke service method doService()"; log.error(msg, ex); } } } } protected abstract void initContextRoot(Request request); public void doService2( final Request request, final Response response, final MessageContext msgContext) throws Exception { ConfigurationContext configurationContext = msgContext.getConfigurationContext(); String soapAction = request.getHeader(HTTPConstants.HEADER_SOAP_ACTION); AxisService service = findServiceWithEndPointClassName(configurationContext, endpointClassName); // TODO: Port this section // // Adjust version and content chunking based on the config // boolean chunked = false; // TransportOutDescription transportOut = msgContext.getTransportOut(); // if (transportOut != null) { // Parameter p = transportOut.getParameter(HTTPConstants.PROTOCOL_VERSION); // if (p != null) { // if (HTTPConstants.HEADER_PROTOCOL_10.equals(p.getValue())) { // ver = HttpVersion.HTTP_1_0; // } // } // if (ver.greaterEquals(HttpVersion.HTTP_1_1)) { // p = transportOut.getParameter(HTTPConstants.HEADER_TRANSFER_ENCODING); // if (p != null) { // if (HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED.equals(p.getValue())) { // chunked = true; // } // } // } // } if (request.getMethod() == Request.GET) { processGetRequest(request, response, service, configurationContext, msgContext, soapAction); } else if (request.getMethod() == Request.POST) { processPostRequest(request, response, service, configurationContext, msgContext, soapAction, jndiResolver); } else { throw new UnsupportedOperationException("[" + request.getMethod() + " ] method not supported"); } // Finalize response OperationContext operationContext = msgContext.getOperationContext(); Object contextWritten = null; Object isTwoChannel = null; if (operationContext != null) { contextWritten = operationContext.getProperty(Constants.RESPONSE_WRITTEN); isTwoChannel = operationContext.getProperty(Constants.DIFFERENT_EPR); } if ((contextWritten != null) && Constants.VALUE_TRUE.equals(contextWritten)) { if ((isTwoChannel != null) && Constants.VALUE_TRUE.equals(isTwoChannel)) { response.setStatusCode(202); return; } response.setStatusCode(200); } else { response.setStatusCode(202); } } public void destroy() { } /** * Resolves the Axis Service associated with the endPointClassName * @param cfgCtx * @param endPointClassName */ private AxisService findServiceWithEndPointClassName(ConfigurationContext cfgCtx, String endPointClassName) { // Visit all the AxisServiceGroups. Iterator svcGrpIter = cfgCtx.getAxisConfiguration().getServiceGroups(); while (svcGrpIter.hasNext()) { // Visit all the AxisServices AxisServiceGroup svcGrp = (AxisServiceGroup) svcGrpIter.next(); Iterator svcIter = svcGrp.getServices(); while (svcIter.hasNext()) { AxisService service = (AxisService) svcIter.next(); // Grab the Parameter that stores the ServiceClass. String epc = (String)service.getParameter("ServiceClass").getValue(); if (epc != null) { // If we have a match, then just return the AxisService now. if (endPointClassName.equals(epc)) { return service; } } } } return null; } public class Axis2TransportInfo implements OutTransportInfo { private Response response; public Axis2TransportInfo(Response response) { this.response = response; } public void setContentType(String contentType) { response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); } } class Axis2RequestResponseTransport implements RequestResponseTransport { private Response response; private CountDownLatch responseReadySignal = new CountDownLatch(1); RequestResponseTransportStatus status = RequestResponseTransportStatus.INITIAL; AxisFault faultToBeThrownOut = null; Axis2RequestResponseTransport(Response response) { this.response = response; } public void acknowledgeMessage(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("acknowledgeMessage"); } if (log.isDebugEnabled()) { log.debug("Acking one-way request"); } response.setContentType("text/xml; charset=" + msgContext.getProperty("message.character-set-encoding")); response.setStatusCode(202); try { response.flushBuffer(); } catch (IOException e) { throw new AxisFault("Error sending acknowledgement", e); } signalResponseReady(); } public void awaitResponse() throws InterruptedException, AxisFault { if (log.isDebugEnabled()) { log.debug("Blocking servlet thread -- awaiting response"); } status = RequestResponseTransportStatus.WAITING; responseReadySignal.await(); if (faultToBeThrownOut != null) { throw faultToBeThrownOut; } } public void signalFaultReady(AxisFault fault) { faultToBeThrownOut = fault; signalResponseReady(); } public void signalResponseReady() { if (log.isDebugEnabled()) { log.debug("Signalling response available"); } status = RequestResponseTransportStatus.SIGNALLED; responseReadySignal.countDown(); } public RequestResponseTransportStatus getStatus() { return status; } } class WSDLGeneratorImpl implements WsdlGenerator { private Definition def; public WSDLGeneratorImpl(Definition def) { this.def = def; } public WsdlComposite generateWsdl(String implClass, String bindingType) throws WebServiceException { // Need WSDL generation code WsdlComposite composite = new WsdlComposite(); composite.setWsdlFileName(implClass); HashMap<String, Definition> testMap = new HashMap<String, Definition>(); testMap.put(composite.getWsdlFileName(), def); composite.setWsdlDefinition(testMap); return composite; } } protected void processGetRequest(Request request, Response response, AxisService service, ConfigurationContext configurationContext, MessageContext msgContext, String soapAction) throws Exception{ String servicePath = configurationContext.getServiceContextPath(); //This is needed as some cases the servicePath contains two // at the beginning. while (servicePath.startsWith("/")) { servicePath = servicePath.substring(1); } final String contextPath = "/" + servicePath; URI uri = request.getURI(); String path = uri.getPath(); String serviceName = service.getName(); if (!path.startsWith(contextPath)) { response.setStatusCode(301); response.setHeader("Location", contextPath); return; } if (uri.toString().indexOf("?") < 0) { if (!path.endsWith(contextPath)) { if (serviceName.indexOf("/") < 0) { String res = HTTPTransportReceiver.printServiceHTML(serviceName, configurationContext); PrintWriter pw = new PrintWriter(response.getOutputStream()); pw.write(res); pw.flush(); return; } } } //TODO: Has to implement if (uri.getQuery().startsWith("wsdl2")) { if (service != null) { service.printWSDL2(response.getOutputStream()); return; } } if (uri.getQuery().startsWith("wsdl")) { if (portInfo.getWsdlFile() != null && !portInfo.getWsdlFile().equals("")) { //wsdl file has been provided Definition wsdlDefinition = new AxisServiceGenerator().getWSDLDefition(portInfo, configurationBaseUrl, classLoader); if(wsdlDefinition != null){ String portName = portInfo.getWsdlPort().getLocalPart(); QName qName = portInfo.getWsdlService(); if (qName == null) { qName = new QName(service.getTargetNamespace(), service.getName()); } if (portName == null) { portName = service.getEndpointName(); } if(qName == null || portName == null) { log.info("Unable to call updateServices ["+ qName + "][" + portName +"]"); } else { log.info("calling updateServices ["+ qName + "][" + portName +"]"); updateServices(qName, portName, wsdlDefinition, request); } WSDLFactory factory = WSDLFactory.newInstance(); WSDLWriter writer = factory.newWSDLWriter(); writer.writeWSDL(wsdlDefinition, response.getOutputStream()); return; } }else { service.printWSDL(response.getOutputStream()); return; } } //TODO: Not working properly and do we need to have these requests ? if (uri.getQuery().startsWith("xsd=")) { String schemaName = uri.getQuery().substring(uri.getQuery().lastIndexOf("=") + 1); if (service != null) { //run the population logic just to be sure service.populateSchemaMappings(); //write out the correct schema Map schemaTable = service.getSchemaMappingTable(); final XmlSchema schema = (XmlSchema) schemaTable.get(schemaName); //schema found - write it to the stream if (schema != null) { schema.write(response.getOutputStream()); return; } else { // no schema available by that name - send 404 response.setStatusCode(404); return; } } } //cater for named xsds - check for the xsd name if (uri.getQuery().startsWith("xsd")) { if (service != null) { response.setContentType("text/xml"); response.setHeader("Transfer-Encoding", "chunked"); service.printSchema(response.getOutputStream()); response.getOutputStream().close(); return; } } msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); InvocationResponse processed = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), null); if (!processed.equals(InvocationResponse.CONTINUE)) { response.setStatusCode(200); String s = HTTPTransportReceiver.getServicesHTML(configurationContext); PrintWriter pw = new PrintWriter(response.getOutputStream()); pw.write(s); pw.flush(); } } protected void setMsgContextProperties(MessageContext msgContext, AxisService service, Response response, Request request) { //BindingImpl binding = new BindingImpl("GeronimoBinding"); //binding.setHandlerChain(chain); //msgContext.setProperty(JAXWSMessageReceiver.PARAM_BINDING, binding); // deal with POST request msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL, new Axis2RequestResponseTransport(response)); msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getURI().toString()); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP); HttpServletRequest servletRequest = (HttpServletRequest)request.getAttribute(WebServiceContainer.SERVLET_REQUEST); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST, servletRequest); HttpServletResponse servletResponse = (HttpServletResponse)request.getAttribute(WebServiceContainer.SERVLET_RESPONSE); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE, servletResponse); ServletContext servletContext = (ServletContext)request.getAttribute(WebServiceContainer.SERVLET_CONTEXT); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETCONTEXT, servletContext); } protected void processPostRequest (Request request, Response response, AxisService service, ConfigurationContext configurationContext, MessageContext msgContext, String soapAction, JNDIResolver jndiResolver) throws Exception { String contenttype = request.getHeader(HTTPConstants.HEADER_CONTENT_TYPE); msgContext.setAxisService(service); configurationContext.fillServiceContextAndServiceGroupContext(msgContext); ServiceGroupContext serviceGroupContext = msgContext.getServiceGroupContext(); DependencyManager.initService(serviceGroupContext); //endpointInstance = msgContext.getServiceContext().getProperty(ServiceContext.SERVICE_OBJECT); setMsgContextProperties(msgContext, service, response, request); HTTPTransportUtils.processHTTPPostRequest( msgContext, request.getInputStream(), response.getOutputStream(), contenttype, soapAction, request.getURI().getPath()); } private void updateServices(QName serviceName, String portName, Definition def, Request request) throws Exception { boolean updated = false; Map services = def.getServices(); if (services != null) { Iterator serviceIterator = services.entrySet().iterator(); while (serviceIterator.hasNext()) { Map.Entry serviceEntry = (Map.Entry) serviceIterator.next(); QName currServiceName = (QName) serviceEntry.getKey(); if (currServiceName.equals(serviceName)) { Service service = (Service) serviceEntry.getValue(); updatePorts(portName, service, request); updated = true; } else { def.removeService(currServiceName); } } } if (!updated) { log.warn("WSDL '" + serviceName.getLocalPart() + "' service not found."); } } private void updatePorts(String portName, Service service, Request request) throws Exception { boolean updated = false; Map ports = service.getPorts(); if (ports != null) { Iterator portIterator = ports.entrySet().iterator(); while (portIterator.hasNext()) { Map.Entry portEntry = (Map.Entry) portIterator.next(); String currPortName = (String) portEntry.getKey(); if (currPortName.equals(portName)) { Port port = (Port) portEntry.getValue(); updatePortLocation(request, port); updated = true; } else { service.removePort(currPortName); } } } if (!updated) { log.warn("WSDL '" + portName + "' port not found."); } } private void updatePortLocation(Request request, Port port) throws URISyntaxException { List<?> exts = port.getExtensibilityElements(); if (exts != null && exts.size() > 0) { URI requestURI = request.getURI(); URI serviceURI = new URI(requestURI.getScheme(), null, requestURI.getHost(), requestURI.getPort(), requestURI.getPath(), null, null); ExtensibilityElement el = (ExtensibilityElement) exts.get(0); if(el instanceof SOAP12Address){ SOAP12Address add = (SOAP12Address)el; add.setLocationURI(serviceURI.toString()); } else if (el instanceof SOAPAddress) { SOAPAddress add = (SOAPAddress)el; add.setLocationURI(serviceURI.toString()); } } } }
modules/geronimo-axis2/src/main/java/org/apache/geronimo/axis2/Axis2WebServiceContainer.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.axis2; import org.apache.axiom.om.util.UUIDGenerator; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingHelper; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.TransportInDescription; import org.apache.axis2.description.TransportOutDescription; import org.apache.axis2.engine.AxisEngine; import org.apache.axis2.engine.DependencyManager; import org.apache.axis2.engine.Handler.InvocationResponse; import org.apache.axis2.jaxws.description.builder.WsdlComposite; import org.apache.axis2.jaxws.description.builder.WsdlGenerator; import org.apache.axis2.jaxws.server.JAXWSMessageReceiver; import org.apache.axis2.transport.OutTransportInfo; import org.apache.axis2.transport.RequestResponseTransport; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.transport.http.HTTPTransportReceiver; import org.apache.axis2.transport.http.HTTPTransportUtils; import org.apache.axis2.transport.http.util.RESTUtil; import org.apache.axis2.util.MessageContextBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.jaxws.JAXWSUtils; import org.apache.geronimo.jaxws.JNDIResolver; import org.apache.geronimo.jaxws.PortInfo; import org.apache.geronimo.jaxws.ServerJNDIResolver; import org.apache.geronimo.webservices.WebServiceContainer; import org.apache.geronimo.webservices.saaj.SAAJUniverse; import org.apache.ws.commons.schema.XmlSchema; import javax.naming.Context; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.wsdl.Definition; import javax.wsdl.Service; import javax.wsdl.Port; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.soap.SOAPAddress; import javax.wsdl.extensions.soap12.SOAP12Address; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLWriter; import javax.xml.namespace.QName; import javax.xml.ws.WebServiceException; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URL; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.List; import java.util.concurrent.CountDownLatch; /** * @version $Rev$ $Date$ */ public abstract class Axis2WebServiceContainer implements WebServiceContainer { private static final Log log = LogFactory.getLog(Axis2WebServiceContainer.class); public static final String REQUEST = Axis2WebServiceContainer.class.getName() + "@Request"; public static final String RESPONSE = Axis2WebServiceContainer.class.getName() + "@Response"; private transient final ClassLoader classLoader; private final String endpointClassName; protected org.apache.geronimo.jaxws.PortInfo portInfo; protected ConfigurationContext configurationContext; private JNDIResolver jndiResolver; private AxisService service; private URL configurationBaseUrl; public Axis2WebServiceContainer(PortInfo portInfo, String endpointClassName, ClassLoader classLoader, Context context, URL configurationBaseUrl) { this.classLoader = classLoader; this.endpointClassName = endpointClassName; this.portInfo = portInfo; this.configurationBaseUrl = configurationBaseUrl; try { configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext(); //check to see if the wsdlLocation property is set in portInfo, //if not checking if wsdlLocation exists in annotation //if already set, annotation should not overwrite it. if (portInfo.getWsdlFile() == null || portInfo.getWsdlFile().equals("")){ Class clazz = classLoader.loadClass(endpointClassName); //getwsdllocation from annotation if it exists if (JAXWSUtils.containsWsdlLocation(clazz, classLoader)) portInfo.setWsdlFile(JAXWSUtils.getServiceWsdlLocation(clazz, classLoader)); } if(portInfo.getWsdlFile() != null && !portInfo.getWsdlFile().equals("")){ //WSDL file Has been provided AxisServiceGenerator serviceGen = new AxisServiceGenerator(); service = serviceGen.getServiceFromWSDL(portInfo, endpointClassName, configurationBaseUrl, classLoader); }else { //No WSDL, Axis2 will handle it. Is it ? service = AxisService.createService(endpointClassName, configurationContext.getAxisConfiguration(), JAXWSMessageReceiver.class); } service.setScope(Constants.SCOPE_APPLICATION); configurationContext.getAxisConfiguration().addService(service); } catch (AxisFault af) { throw new RuntimeException(af); } catch (Exception e) { throw new RuntimeException(e); } jndiResolver = new ServerJNDIResolver(context); } public void getWsdl(Request request, Response response) throws Exception { doService(request, response); } public void invoke(Request request, Response response) throws Exception { SAAJUniverse universe = new SAAJUniverse(); universe.set(SAAJUniverse.AXIS2); try { doService(request, response); } finally { universe.unset(); } } protected void doService(final Request request, final Response response) throws Exception { initContextRoot(request); if (log.isDebugEnabled()) { log.debug("Target URI: " + request.getURI()); } MessageContext msgContext = new MessageContext(); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP); msgContext.setProperty(MessageContext.REMOTE_ADDR, request.getRemoteAddr()); try { TransportOutDescription transportOut = this.configurationContext.getAxisConfiguration() .getTransportOut(Constants.TRANSPORT_HTTP); TransportInDescription transportIn = this.configurationContext.getAxisConfiguration() .getTransportIn(Constants.TRANSPORT_HTTP); msgContext.setConfigurationContext(this.configurationContext); //TODO: Port this segment for session support. // String sessionKey = (String) this.httpcontext.getAttribute(HTTPConstants.COOKIE_STRING); // if (this.configurationContext.getAxisConfiguration().isManageTransportSession()) { // SessionContext sessionContext = this.sessionManager.getSessionContext(sessionKey); // msgContext.setSessionContext(sessionContext); // } msgContext.setTransportIn(transportIn); msgContext.setTransportOut(transportOut); msgContext.setServiceGroupContextId(UUIDGenerator.getUUID()); msgContext.setServerSide(true); // // set the transport Headers // HashMap headerMap = new HashMap(); // for (Iterator it = request.headerIterator(); it.hasNext();) { // Header header = (Header) it.next(); // headerMap.put(header.getName(), header.getValue()); // } // msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); // // this.httpcontext.setAttribute(AxisParams.MESSAGE_CONTEXT, msgContext); doService2(request, response, msgContext); } catch (Throwable e) { try { AxisEngine engine = new AxisEngine(this.configurationContext); msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e); // If the fault is not going along the back channel we should be 202ing if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatusCode(202); } else { response.setStatusCode(500); response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/plain"); PrintWriter pw = new PrintWriter(response.getOutputStream()); e.printStackTrace(pw); pw.flush(); String msg = "Exception occurred while trying to invoke service method doService()"; log.error(msg, e); } engine.sendFault(faultContext); } catch (Exception ex) { if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatusCode(202); } else { response.setStatusCode(500); response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, "text/plain"); PrintWriter pw = new PrintWriter(response.getOutputStream()); ex.printStackTrace(pw); pw.flush(); String msg = "Exception occurred while trying to invoke service method doService()"; log.error(msg, ex); } } } } protected abstract void initContextRoot(Request request); public void doService2( final Request request, final Response response, final MessageContext msgContext) throws Exception { ConfigurationContext configurationContext = msgContext.getConfigurationContext(); String soapAction = request.getHeader(HTTPConstants.HEADER_SOAP_ACTION); AxisService service = findServiceWithEndPointClassName(configurationContext, endpointClassName); // TODO: Port this section // // Adjust version and content chunking based on the config // boolean chunked = false; // TransportOutDescription transportOut = msgContext.getTransportOut(); // if (transportOut != null) { // Parameter p = transportOut.getParameter(HTTPConstants.PROTOCOL_VERSION); // if (p != null) { // if (HTTPConstants.HEADER_PROTOCOL_10.equals(p.getValue())) { // ver = HttpVersion.HTTP_1_0; // } // } // if (ver.greaterEquals(HttpVersion.HTTP_1_1)) { // p = transportOut.getParameter(HTTPConstants.HEADER_TRANSFER_ENCODING); // if (p != null) { // if (HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED.equals(p.getValue())) { // chunked = true; // } // } // } // } if (request.getMethod() == Request.GET) { processGetRequest(request, response, service, configurationContext, msgContext, soapAction); } else if (request.getMethod() == Request.POST) { processPostRequest(request, response, service, configurationContext, msgContext, soapAction, jndiResolver); } else { throw new UnsupportedOperationException("[" + request.getMethod() + " ] method not supported"); } // Finalize response OperationContext operationContext = msgContext.getOperationContext(); Object contextWritten = null; Object isTwoChannel = null; if (operationContext != null) { contextWritten = operationContext.getProperty(Constants.RESPONSE_WRITTEN); isTwoChannel = operationContext.getProperty(Constants.DIFFERENT_EPR); } if ((contextWritten != null) && Constants.VALUE_TRUE.equals(contextWritten)) { if ((isTwoChannel != null) && Constants.VALUE_TRUE.equals(isTwoChannel)) { response.setStatusCode(202); return; } response.setStatusCode(200); } else { response.setStatusCode(202); } } public void destroy() { } /** * Resolves the Axis Service associated with the endPointClassName * @param cfgCtx * @param endPointClassName */ private AxisService findServiceWithEndPointClassName(ConfigurationContext cfgCtx, String endPointClassName) { // Visit all the AxisServiceGroups. Iterator svcGrpIter = cfgCtx.getAxisConfiguration().getServiceGroups(); while (svcGrpIter.hasNext()) { // Visit all the AxisServices AxisServiceGroup svcGrp = (AxisServiceGroup) svcGrpIter.next(); Iterator svcIter = svcGrp.getServices(); while (svcIter.hasNext()) { AxisService service = (AxisService) svcIter.next(); // Grab the Parameter that stores the ServiceClass. String epc = (String)service.getParameter("ServiceClass").getValue(); if (epc != null) { // If we have a match, then just return the AxisService now. if (endPointClassName.equals(epc)) { return service; } } } } return null; } public class Axis2TransportInfo implements OutTransportInfo { private Response response; public Axis2TransportInfo(Response response) { this.response = response; } public void setContentType(String contentType) { response.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); } } class Axis2RequestResponseTransport implements RequestResponseTransport { private Response response; private CountDownLatch responseReadySignal = new CountDownLatch(1); RequestResponseTransportStatus status = RequestResponseTransportStatus.INITIAL; AxisFault faultToBeThrownOut = null; Axis2RequestResponseTransport(Response response) { this.response = response; } public void acknowledgeMessage(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("acknowledgeMessage"); } if (log.isDebugEnabled()) { log.debug("Acking one-way request"); } response.setContentType("text/xml; charset=" + msgContext.getProperty("message.character-set-encoding")); response.setStatusCode(202); try { response.flushBuffer(); } catch (IOException e) { throw new AxisFault("Error sending acknowledgement", e); } signalResponseReady(); } public void awaitResponse() throws InterruptedException, AxisFault { if (log.isDebugEnabled()) { log.debug("Blocking servlet thread -- awaiting response"); } status = RequestResponseTransportStatus.WAITING; responseReadySignal.await(); if (faultToBeThrownOut != null) { throw faultToBeThrownOut; } } public void signalFaultReady(AxisFault fault) { faultToBeThrownOut = fault; signalResponseReady(); } public void signalResponseReady() { if (log.isDebugEnabled()) { log.debug("Signalling response available"); } status = RequestResponseTransportStatus.SIGNALLED; responseReadySignal.countDown(); } public RequestResponseTransportStatus getStatus() { return status; } } class WSDLGeneratorImpl implements WsdlGenerator { private Definition def; public WSDLGeneratorImpl(Definition def) { this.def = def; } public WsdlComposite generateWsdl(String implClass, String bindingType) throws WebServiceException { // Need WSDL generation code WsdlComposite composite = new WsdlComposite(); composite.setWsdlFileName(implClass); HashMap<String, Definition> testMap = new HashMap<String, Definition>(); testMap.put(composite.getWsdlFileName(), def); composite.setWsdlDefinition(testMap); return composite; } } protected void processGetRequest(Request request, Response response, AxisService service, ConfigurationContext configurationContext, MessageContext msgContext, String soapAction) throws Exception{ String servicePath = configurationContext.getServiceContextPath(); //This is needed as some cases the servicePath contains two // at the beginning. while (servicePath.startsWith("/")) { servicePath = servicePath.substring(1); } final String contextPath = "/" + servicePath; URI uri = request.getURI(); String path = uri.getPath(); String serviceName = service.getName(); if (!path.startsWith(contextPath)) { response.setStatusCode(301); response.setHeader("Location", contextPath); return; } if (uri.toString().indexOf("?") < 0) { if (!path.endsWith(contextPath)) { if (serviceName.indexOf("/") < 0) { String res = HTTPTransportReceiver.printServiceHTML(serviceName, configurationContext); PrintWriter pw = new PrintWriter(response.getOutputStream()); pw.write(res); pw.flush(); return; } } } //TODO: Has to implement if (uri.getQuery().startsWith("wsdl2")) { if (service != null) { service.printWSDL2(response.getOutputStream()); return; } } if (uri.getQuery().startsWith("wsdl")) { if (portInfo.getWsdlFile() != null && !portInfo.getWsdlFile().equals("")) { //wsdl file has been provided Definition wsdlDefinition = new AxisServiceGenerator().getWSDLDefition(portInfo, configurationBaseUrl, classLoader); if(wsdlDefinition != null){ String portName = portInfo.getPortName(); QName qName = portInfo.getWsdlService(); if (qName == null) { qName = new QName(service.getTargetNamespace(), service.getName()); } if (portName == null) { portName = service.getEndpointName(); } if(qName == null || portName == null) { log.info("Unable to call updateServices ["+ qName + "][" + portName +"]"); } else { log.info("calling updateServices ["+ qName + "][" + portName +"]"); updateServices(qName, portName, wsdlDefinition, request); } WSDLFactory factory = WSDLFactory.newInstance(); WSDLWriter writer = factory.newWSDLWriter(); writer.writeWSDL(wsdlDefinition, response.getOutputStream()); return; } }else { service.printWSDL(response.getOutputStream()); return; } } //TODO: Not working properly and do we need to have these requests ? if (uri.getQuery().startsWith("xsd=")) { String schemaName = uri.getQuery().substring(uri.getQuery().lastIndexOf("=") + 1); if (service != null) { //run the population logic just to be sure service.populateSchemaMappings(); //write out the correct schema Map schemaTable = service.getSchemaMappingTable(); final XmlSchema schema = (XmlSchema) schemaTable.get(schemaName); //schema found - write it to the stream if (schema != null) { schema.write(response.getOutputStream()); return; } else { // no schema available by that name - send 404 response.setStatusCode(404); return; } } } //cater for named xsds - check for the xsd name if (uri.getQuery().startsWith("xsd")) { if (service != null) { response.setContentType("text/xml"); response.setHeader("Transfer-Encoding", "chunked"); service.printSchema(response.getOutputStream()); response.getOutputStream().close(); return; } } msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); InvocationResponse processed = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), null); if (!processed.equals(InvocationResponse.CONTINUE)) { response.setStatusCode(200); String s = HTTPTransportReceiver.getServicesHTML(configurationContext); PrintWriter pw = new PrintWriter(response.getOutputStream()); pw.write(s); pw.flush(); } } protected void setMsgContextProperties(MessageContext msgContext, AxisService service, Response response, Request request) { //BindingImpl binding = new BindingImpl("GeronimoBinding"); //binding.setHandlerChain(chain); //msgContext.setProperty(JAXWSMessageReceiver.PARAM_BINDING, binding); // deal with POST request msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new Axis2TransportInfo(response)); msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL, new Axis2RequestResponseTransport(response)); msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getURI().toString()); msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP); HttpServletRequest servletRequest = (HttpServletRequest)request.getAttribute(WebServiceContainer.SERVLET_REQUEST); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST, servletRequest); HttpServletResponse servletResponse = (HttpServletResponse)request.getAttribute(WebServiceContainer.SERVLET_RESPONSE); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE, servletResponse); ServletContext servletContext = (ServletContext)request.getAttribute(WebServiceContainer.SERVLET_CONTEXT); msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETCONTEXT, servletContext); } protected void processPostRequest (Request request, Response response, AxisService service, ConfigurationContext configurationContext, MessageContext msgContext, String soapAction, JNDIResolver jndiResolver) throws Exception { String contenttype = request.getHeader(HTTPConstants.HEADER_CONTENT_TYPE); msgContext.setAxisService(service); configurationContext.fillServiceContextAndServiceGroupContext(msgContext); ServiceGroupContext serviceGroupContext = msgContext.getServiceGroupContext(); DependencyManager.initService(serviceGroupContext); //endpointInstance = msgContext.getServiceContext().getProperty(ServiceContext.SERVICE_OBJECT); setMsgContextProperties(msgContext, service, response, request); HTTPTransportUtils.processHTTPPostRequest( msgContext, request.getInputStream(), response.getOutputStream(), contenttype, soapAction, request.getURI().getPath()); } private void updateServices(QName serviceName, String portName, Definition def, Request request) throws Exception { boolean updated = false; Map services = def.getServices(); if (services != null) { Iterator serviceIterator = services.entrySet().iterator(); while (serviceIterator.hasNext()) { Map.Entry serviceEntry = (Map.Entry) serviceIterator.next(); QName currServiceName = (QName) serviceEntry.getKey(); if (currServiceName.equals(serviceName)) { Service service = (Service) serviceEntry.getValue(); updatePorts(portName, service, request); updated = true; } else { def.removeService(currServiceName); } } } if (!updated) { log.warn("WSDL '" + serviceName.getLocalPart() + "' service not found."); } } private void updatePorts(String portName, Service service, Request request) throws Exception { boolean updated = false; Map ports = service.getPorts(); if (ports != null) { Iterator portIterator = ports.entrySet().iterator(); while (portIterator.hasNext()) { Map.Entry portEntry = (Map.Entry) portIterator.next(); String currPortName = (String) portEntry.getKey(); if (currPortName.equals(portName)) { Port port = (Port) portEntry.getValue(); updatePortLocation(request, port); updated = true; } else { service.removePort(currPortName); } } } if (!updated) { log.warn("WSDL '" + portName + "' port not found."); } } private void updatePortLocation(Request request, Port port) throws URISyntaxException { List<?> exts = port.getExtensibilityElements(); if (exts != null && exts.size() > 0) { URI requestURI = request.getURI(); URI serviceURI = new URI(requestURI.getScheme(), null, requestURI.getHost(), requestURI.getPort(), requestURI.getPath(), null, null); ExtensibilityElement el = (ExtensibilityElement) exts.get(0); if(el instanceof SOAP12Address){ SOAP12Address add = (SOAP12Address)el; add.setLocationURI(serviceURI.toString()); } else if (el instanceof SOAPAddress) { SOAPAddress add = (SOAPAddress)el; add.setLocationURI(serviceURI.toString()); } } } }
Fix for GERONIMO-3074 - Axis2: portname isn't set correctly git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@526756 13f79535-47bb-0310-9956-ffa450edef68
modules/geronimo-axis2/src/main/java/org/apache/geronimo/axis2/Axis2WebServiceContainer.java
Fix for GERONIMO-3074 - Axis2: portname isn't set correctly
<ide><path>odules/geronimo-axis2/src/main/java/org/apache/geronimo/axis2/Axis2WebServiceContainer.java <ide> if (portInfo.getWsdlFile() != null && !portInfo.getWsdlFile().equals("")) { //wsdl file has been provided <ide> Definition wsdlDefinition = new AxisServiceGenerator().getWSDLDefition(portInfo, configurationBaseUrl, classLoader); <ide> if(wsdlDefinition != null){ <del> String portName = portInfo.getPortName(); <add> String portName = portInfo.getWsdlPort().getLocalPart(); <ide> QName qName = portInfo.getWsdlService(); <ide> if (qName == null) { <ide> qName = new QName(service.getTargetNamespace(), service.getName());
Java
apache-2.0
cb58e923552ec512f89176295fc49d83073e9120
0
timothyjward/bndtools,bjhargrave/bndtools,grfield/bndtools,lostiniceland/bndtools,bndtools/bndtools,seanbright/bndtools,bjhargrave/bndtools,wodencafe/bndtools,lostiniceland/bndtools,seanbright/bndtools,wodencafe/bndtools,psoreide/bnd,grfield/bndtools,bndtools/bndtools,lostiniceland/bndtools,pkriens/bndtools,timothyjward/bndtools,wodencafe/bndtools,wodencafe/bndtools,bndtools/bndtools,grfield/bndtools,pkriens/bndtools,lostiniceland/bndtools,timothyjward/bndtools,lostiniceland/bndtools,seanbright/bndtools,njbartlett/bndtools,pkriens/bndtools,pkriens/bndtools,pkriens/bndtools,bndtools/bndtools,njbartlett/bndtools,njbartlett/bndtools,timothyjward/bndtools,njbartlett/bndtools,njbartlett/bndtools,bjhargrave/bndtools,bjhargrave/bndtools,lostiniceland/bndtools,pkriens/bndtools,seanbright/bndtools,psoreide/bnd,grfield/bndtools,psoreide/bnd,grfield/bndtools,wodencafe/bndtools,bndtools/bndtools,wodencafe/bndtools,seanbright/bndtools,bjhargrave/bndtools,njbartlett/bndtools,bjhargrave/bndtools,timothyjward/bndtools
/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation *******************************************************************************/ package bndtools.wizards.project; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.MessageFormat; import org.bndtools.api.IProjectTemplate; import org.bndtools.api.ProjectLayout; import org.bndtools.api.ProjectPaths; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageTwo; import org.eclipse.jface.dialogs.ErrorDialog; import aQute.bnd.build.Project; import aQute.bnd.build.model.BndEditModel; import aQute.bnd.osgi.Constants; import bndtools.Plugin; import bndtools.editor.model.BndProject; class NewBndProjectWizard extends AbstractNewBndProjectWizard { public static final String DEFAULT_BUNDLE_VERSION = "0.0.0.${tstamp}"; private final TemplateSelectionWizardPage templatePage = new TemplateSelectionWizardPage(); NewBndProjectWizard(final NewBndProjectWizardPageOne pageOne, final NewJavaProjectWizardPageTwo pageTwo) { super(pageOne, pageTwo); templatePage.addPropertyChangeListener(TemplateSelectionWizardPage.PROP_TEMPLATE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { pageOne.setProjectTemplate((IProjectTemplate) evt.getNewValue()); } }); } @Override public void addPages() { addPage(pageOne); addPage(templatePage); addPage(pageTwo); } /** * Generate the new Bnd model for the project. This implementation simply returns an empty Bnd model. * * @param monitor */ @Override protected BndEditModel generateBndModel(IProgressMonitor monitor) { ProjectPaths bndPaths = ProjectPaths.get(ProjectLayout.BND); BndEditModel model = super.generateBndModel(monitor); ProjectPaths projectPaths = ProjectPaths.get(ProjectLayout.BND); IProjectTemplate template = templatePage.getTemplate(); if (template != null) { model.setBundleVersion(DEFAULT_BUNDLE_VERSION); template.modifyInitialBndModel(model, projectPaths); } try { String name = pageTwo.getJavaProject().getProject().getName(); IPath projectPath = new Path(name).makeAbsolute(); IClasspathEntry[] entries = pageTwo.getJavaProject().getResolvedClasspath(true); int nr = 1; for (IClasspathEntry entry : entries) { if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath srcPath = entry.getPath(); IPath src = srcPath.makeRelativeTo(projectPath); IPath srcOutPath = entry.getOutputLocation(); if (srcOutPath == null) { srcOutPath = pageTwo.getJavaProject().getOutputLocation(); } IPath srcOut = srcOutPath.makeRelativeTo(projectPath); if (nr == 1) { if (!bndPaths.getSrc().equals(src.toString())) { model.genericSet(Constants.DEFAULT_PROP_SRC_DIR, src.toString()); } if (!bndPaths.getBin().equals(srcOut.toString())) { model.genericSet(Constants.DEFAULT_PROP_BIN_DIR, srcOut.toString()); } nr = 2; } else if (nr == 2) { if (!bndPaths.getTestSrc().equals(src.toString())) { model.genericSet(Constants.DEFAULT_PROP_TESTSRC_DIR, src.toString()); } if (!bndPaths.getTestBin().equals(srcOut.toString())) { model.genericSet(Constants.DEFAULT_PROP_TESTBIN_DIR, srcOut.toString()); } nr = 2; } else { // if for some crazy reason we end up with more than 2 paths, we log them in // extension properties (we cannot write comments) but this should never happen // anyway since the second page will not complete if there are not exactly 2 paths // so this could only happen if someone adds another page (that changes them again) model.genericSet("X-WARN-" + nr, "Ignoring source path " + src + " -> " + srcOut); nr++; } } } String projectTargetDir = projectPaths.getTargetDir(); if (!bndPaths.getTargetDir().equals(projectTargetDir)) { model.genericSet(Constants.DEFAULT_PROP_TARGET_DIR, projectTargetDir); } } catch (Exception e) { ErrorDialog.openError(getShell(), "Error", "", new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Error setting paths in Bnd project descriptor file ({0}).", Project.BNDFILE), e)); } return model; } /** * Allows for an IProjectTemplate to modify the new Bnd project * * @param monitor */ @Override protected BndProject generateBndProject(IProject project, IProgressMonitor monitor) { BndProject proj = super.generateBndProject(project, monitor); ProjectPaths projectPaths = ProjectPaths.get(ProjectLayout.BND); IProjectTemplate template = templatePage.getTemplate(); if (template != null) { template.modifyInitialBndProject(proj, projectPaths); } return proj; } }
bndtools.core/src/bndtools/wizards/project/NewBndProjectWizard.java
/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation *******************************************************************************/ package bndtools.wizards.project; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.MessageFormat; import org.bndtools.api.IProjectTemplate; import org.bndtools.api.ProjectLayout; import org.bndtools.api.ProjectPaths; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageTwo; import org.eclipse.jface.dialogs.ErrorDialog; import aQute.bnd.build.Project; import aQute.bnd.build.model.BndEditModel; import aQute.bnd.osgi.Constants; import bndtools.Plugin; import bndtools.editor.model.BndProject; class NewBndProjectWizard extends AbstractNewBndProjectWizard { public static final String DEFAULT_BUNDLE_VERSION = "0.0.0.${tstamp}"; private final TemplateSelectionWizardPage templatePage = new TemplateSelectionWizardPage(); NewBndProjectWizard(final NewBndProjectWizardPageOne pageOne, final NewJavaProjectWizardPageTwo pageTwo) { super(pageOne, pageTwo); templatePage.addPropertyChangeListener(TemplateSelectionWizardPage.PROP_TEMPLATE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { pageOne.setProjectTemplate((IProjectTemplate) evt.getNewValue()); } }); } @Override public void addPages() { addPage(pageOne); addPage(templatePage); addPage(pageTwo); } /** * Generate the new Bnd model for the project. This implementation simply returns an empty Bnd model. * * @param monitor */ @Override protected BndEditModel generateBndModel(IProgressMonitor monitor) { ProjectPaths bndPaths = ProjectPaths.get(ProjectLayout.BND); BndEditModel model = super.generateBndModel(monitor); ProjectPaths projectPaths = ProjectPaths.get(ProjectLayout.BND); IProjectTemplate template = templatePage.getTemplate(); if (template != null) { model.setBundleVersion(DEFAULT_BUNDLE_VERSION); template.modifyInitialBndModel(model, projectPaths); } try { String name = pageTwo.getJavaProject().getProject().getName(); IPath projectPath = new Path(name).makeAbsolute(); IClasspathEntry[] entries = pageTwo.getJavaProject().getResolvedClasspath(true); int nr = 1; for (IClasspathEntry entry : entries) { if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath srcPath = entry.getPath(); IPath src = srcPath.makeRelativeTo(projectPath); IPath srcOutPath = entry.getOutputLocation(); if (srcOutPath == null) { srcOutPath = pageTwo.getJavaProject().getOutputLocation(); } IPath srcOut = srcOutPath.makeRelativeTo(projectPath); if (nr == 1) { if (!bndPaths.getSrc().equals(src.toString())) { model.genericSet(Constants.DEFAULT_PROP_SRC_DIR, src.toString()); } if (!bndPaths.getBin().equals(srcOut.toString())) { model.genericSet(Constants.DEFAULT_PROP_BIN_DIR, srcOut.toString()); } nr = 2; } else if (nr == 2) { if (!bndPaths.getTestSrc().equals(src.toString())) { model.genericSet(Constants.DEFAULT_PROP_TESTSRC_DIR, src.toString()); } if (!bndPaths.getTestBin().equals(srcOut.toString())) { model.genericSet(Constants.DEFAULT_PROP_TESTBIN_DIR, srcOut.toString()); } nr = 2; } else { // if for some crazy reason we end up with more than 2 paths, we log them in // extension properties (we cannot write comments) but this should never happen // anyway since the second page will not complete if there are not exactly 2 paths // so this could only happen if someone adds another page (that changes them again) model.genericSet("X-WARN-" + nr, "Ignoring source path " + src + " -> " + srcOut); nr++; } } } } catch (Exception e) { ErrorDialog.openError(getShell(), "Error", "", new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Error setting paths in Bnd project descriptor file ({0}).", Project.BNDFILE), e)); } return model; } /** * Allows for an IProjectTemplate to modify the new Bnd project * * @param monitor */ @Override protected BndProject generateBndProject(IProject project, IProgressMonitor monitor) { BndProject proj = super.generateBndProject(project, monitor); ProjectPaths projectPaths = ProjectPaths.get(ProjectLayout.BND); IProjectTemplate template = templatePage.getTemplate(); if (template != null) { template.modifyInitialBndProject(proj, projectPaths); } return proj; } }
Also setup the targetDir (in the bnd.bnd file) when it's not the default Signed-off-by: Ferry Huberts <[email protected]>
bndtools.core/src/bndtools/wizards/project/NewBndProjectWizard.java
Also setup the targetDir (in the bnd.bnd file) when it's not the default
<ide><path>ndtools.core/src/bndtools/wizards/project/NewBndProjectWizard.java <ide> } <ide> } <ide> } <add> <add> String projectTargetDir = projectPaths.getTargetDir(); <add> if (!bndPaths.getTargetDir().equals(projectTargetDir)) { <add> model.genericSet(Constants.DEFAULT_PROP_TARGET_DIR, projectTargetDir); <add> } <ide> } catch (Exception e) { <ide> ErrorDialog.openError(getShell(), "Error", "", new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Error setting paths in Bnd project descriptor file ({0}).", Project.BNDFILE), e)); <ide> }
Java
apache-2.0
ac1d978196a86151e0b1315b176d1e730196bc80
0
apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.seaborne.dboe.transaction; import java.util.function.Supplier ; import org.apache.jena.query.ReadWrite ; /** Application utilities for transactions. */ public class Txn { /** Execute the Runnable in a read transaction. * Nested transactions are not supported. */ public static <T extends Transactional> void executeRead(T txn, Runnable r) { txn.begin(ReadWrite.READ) ; try { r.run(); } finally { txn.end() ; } } /** Execute and return a value in a read transaction * Nested transactions are not supported. */ public static <T extends Transactional, X> X executeReadReturn(T txn, Supplier<X> r) { try { txn.begin(ReadWrite.READ) ; return r.get() ; } finally { txn.end() ; } } /** Execute the Runnable in a write transaction * Nested transaction are not supported. */ public static <T extends Transactional> void executeWrite(T txn, Runnable r) { txn.begin(ReadWrite.WRITE) ; try { r.run(); txn.commit(); } catch (Throwable th) { txn.abort(); throw th ; } finally { txn.end(); } } /** Execute the Runnable in a write transaction * Nested transaction are not supported. */ public static <T extends Transactional, X> X executeWriteReturn(Transactional txn, Supplier<X> r) { txn.begin(ReadWrite.WRITE) ; try { X x = r.get() ; txn.commit() ; return x ; } catch (Throwable th) { txn.abort(); throw th ; } finally { txn.end(); } } // ---- Thread /** Create a thread-backed delayed READ transaction action. */ public static ThreadTxn threadTxnRead(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.READ, action, false) ; } /** Create a thread-backed delayed WRITE action. * If called from inside a write transaction on the {@code trans}, * this will deadlock. */ public static ThreadTxn threadTxnWrite(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.WRITE, action, true) ; } /** Create a thread-backed delayed WRITE-abort action (testing). */ public static ThreadTxn threadTxnWriteAbort(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.WRITE, action, false) ; } }
dboe-transaction/src/main/java/org/seaborne/dboe/transaction/Txn.java
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.seaborne.dboe.transaction; import java.util.function.Supplier ; import org.apache.jena.query.ReadWrite ; /** Application utilities for transactions. */ public class Txn { /** Execute the Runnable in a read transaction. * Nested transactions are not supported. */ public static <T extends Transactional> void executeRead(T txn, Runnable r) { txn.begin(ReadWrite.READ) ; r.run(); txn.end() ; } /** Execute and return a value in a read transaction * Nested transactions are not supported. */ public static <T extends Transactional, X> X executeReadReturn(T txn, Supplier<X> r) { txn.begin(ReadWrite.READ) ; X x = r.get() ; txn.end() ; return x ; } /** Execute the Runnable in a write transaction * Nested transaction are not supported. */ public static <T extends Transactional> void executeWrite(T txn, Runnable r) { txn.begin(ReadWrite.WRITE) ; try { r.run(); } catch (Throwable th) { txn.abort(); txn.end(); throw th ; } txn.commit() ; txn.end() ; } /** Execute the Runnable in a write transaction * Nested transaction are not supported. */ public static <T extends Transactional, X> X executeWriteReturn(Transactional txn, Supplier<X> r) { txn.begin(ReadWrite.WRITE) ; X x = r.get() ; txn.commit() ; txn.end() ; return x ; } // ---- Thread /** Create a thread-backed delayed READ transaction action. */ public static ThreadTxn threadTxnRead(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.READ, action, false) ; } /** Create a thread-backed delayed WRITE action. * If called from inside a write transaction on the {@code trans}, * this will deadlock. */ public static ThreadTxn threadTxnWrite(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.WRITE, action, true) ; } /** Create a thread-backed delayed WRITE-abort action (testing). */ public static ThreadTxn threadTxnWriteAbort(Transactional trans, Runnable action) { return ThreadTxn.create(trans, ReadWrite.WRITE, action, false) ; } }
Use try-finally even on read transactions.
dboe-transaction/src/main/java/org/seaborne/dboe/transaction/Txn.java
Use try-finally even on read transactions.
<ide><path>boe-transaction/src/main/java/org/seaborne/dboe/transaction/Txn.java <ide> */ <ide> public static <T extends Transactional> void executeRead(T txn, Runnable r) { <ide> txn.begin(ReadWrite.READ) ; <del> r.run(); <del> txn.end() ; <add> try { <add> r.run(); <add> } finally { txn.end() ; } <ide> } <ide> <ide> /** Execute and return a value in a read transaction <ide> */ <ide> <ide> public static <T extends Transactional, X> X executeReadReturn(T txn, Supplier<X> r) { <del> txn.begin(ReadWrite.READ) ; <del> X x = r.get() ; <del> txn.end() ; <del> return x ; <add> try { <add> txn.begin(ReadWrite.READ) ; <add> return r.get() ; <add> } finally { txn.end() ; } <ide> } <ide> <ide> /** Execute the Runnable in a write transaction <ide> */ <ide> public static <T extends Transactional> void executeWrite(T txn, Runnable r) { <ide> txn.begin(ReadWrite.WRITE) ; <del> try { r.run(); } <del> catch (Throwable th) { <add> try { <add> r.run(); <add> txn.commit(); <add> } catch (Throwable th) { <ide> txn.abort(); <del> txn.end(); <ide> throw th ; <del> } <del> txn.commit() ; <del> txn.end() ; <add> } finally { txn.end(); } <ide> } <ide> <ide> /** Execute the Runnable in a write transaction <ide> */ <ide> public static <T extends Transactional, X> X executeWriteReturn(Transactional txn, Supplier<X> r) { <ide> txn.begin(ReadWrite.WRITE) ; <del> X x = r.get() ; <del> txn.commit() ; <del> txn.end() ; <del> return x ; <add> try { <add> X x = r.get() ; <add> txn.commit() ; <add> return x ; <add> } catch (Throwable th) { <add> txn.abort(); <add> throw th ; <add> } finally { txn.end(); } <ide> } <ide> <ide> // ---- Thread <ide> public static ThreadTxn threadTxnWriteAbort(Transactional trans, Runnable action) { <ide> return ThreadTxn.create(trans, ReadWrite.WRITE, action, false) ; <ide> } <del> <del> <ide> } <ide>
Java
apache-2.0
error: pathspec 'Examples/Segmentation/WatershedSegmentation1.java' did not match any file(s) known to git
e4e6b82a4b4b3b2b43dfdc3a8fed966b86e67a8d
1
heimdali/ITK,vfonov/ITK,daviddoria/itkHoughTransform,fbudin69500/ITK,BlueBrain/ITK,LucHermitte/ITK,biotrump/ITK,malaterre/ITK,hjmjohnson/ITK,GEHC-Surgery/ITK,malaterre/ITK,vfonov/ITK,hjmjohnson/ITK,CapeDrew/DITK,LucHermitte/ITK,BlueBrain/ITK,atsnyder/ITK,GEHC-Surgery/ITK,CapeDrew/DITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,Kitware/ITK,fuentesdt/InsightToolkit-dev,atsnyder/ITK,blowekamp/ITK,rhgong/itk-with-dom,LucHermitte/ITK,BRAINSia/ITK,fuentesdt/InsightToolkit-dev,daviddoria/itkHoughTransform,malaterre/ITK,itkvideo/ITK,richardbeare/ITK,LucHermitte/ITK,spinicist/ITK,heimdali/ITK,zachary-williamson/ITK,spinicist/ITK,BlueBrain/ITK,BRAINSia/ITK,fbudin69500/ITK,GEHC-Surgery/ITK,eile/ITK,malaterre/ITK,LucasGandel/ITK,CapeDrew/DITK,wkjeong/ITK,biotrump/ITK,cpatrick/ITK-RemoteIO,PlutoniumHeart/ITK,BlueBrain/ITK,biotrump/ITK,hinerm/ITK,jcfr/ITK,hinerm/ITK,jmerkow/ITK,zachary-williamson/ITK,atsnyder/ITK,fedral/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,hendradarwin/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,hinerm/ITK,fuentesdt/InsightToolkit-dev,fuentesdt/InsightToolkit-dev,stnava/ITK,spinicist/ITK,hinerm/ITK,jcfr/ITK,rhgong/itk-with-dom,wkjeong/ITK,InsightSoftwareConsortium/ITK,jcfr/ITK,cpatrick/ITK-RemoteIO,thewtex/ITK,hendradarwin/ITK,hendradarwin/ITK,blowekamp/ITK,itkvideo/ITK,Kitware/ITK,Kitware/ITK,GEHC-Surgery/ITK,itkvideo/ITK,BlueBrain/ITK,hjmjohnson/ITK,PlutoniumHeart/ITK,CapeDrew/DCMTK-ITK,zachary-williamson/ITK,spinicist/ITK,Kitware/ITK,zachary-williamson/ITK,hendradarwin/ITK,ajjl/ITK,eile/ITK,vfonov/ITK,heimdali/ITK,BRAINSia/ITK,daviddoria/itkHoughTransform,jmerkow/ITK,jcfr/ITK,zachary-williamson/ITK,zachary-williamson/ITK,itkvideo/ITK,GEHC-Surgery/ITK,richardbeare/ITK,biotrump/ITK,InsightSoftwareConsortium/ITK,fedral/ITK,BRAINSia/ITK,daviddoria/itkHoughTransform,fedral/ITK,GEHC-Surgery/ITK,daviddoria/itkHoughTransform,rhgong/itk-with-dom,richardbeare/ITK,richardbeare/ITK,LucHermitte/ITK,fuentesdt/InsightToolkit-dev,fbudin69500/ITK,zachary-williamson/ITK,stnava/ITK,msmolens/ITK,stnava/ITK,hendradarwin/ITK,spinicist/ITK,eile/ITK,hinerm/ITK,BlueBrain/ITK,richardbeare/ITK,PlutoniumHeart/ITK,spinicist/ITK,thewtex/ITK,LucasGandel/ITK,blowekamp/ITK,vfonov/ITK,jmerkow/ITK,stnava/ITK,cpatrick/ITK-RemoteIO,fbudin69500/ITK,rhgong/itk-with-dom,malaterre/ITK,CapeDrew/DCMTK-ITK,paulnovo/ITK,Kitware/ITK,PlutoniumHeart/ITK,fuentesdt/InsightToolkit-dev,InsightSoftwareConsortium/ITK,thewtex/ITK,hjmjohnson/ITK,atsnyder/ITK,hendradarwin/ITK,ajjl/ITK,paulnovo/ITK,wkjeong/ITK,LucasGandel/ITK,spinicist/ITK,atsnyder/ITK,itkvideo/ITK,itkvideo/ITK,heimdali/ITK,atsnyder/ITK,InsightSoftwareConsortium/ITK,GEHC-Surgery/ITK,atsnyder/ITK,stnava/ITK,ajjl/ITK,daviddoria/itkHoughTransform,cpatrick/ITK-RemoteIO,heimdali/ITK,blowekamp/ITK,BlueBrain/ITK,stnava/ITK,daviddoria/itkHoughTransform,paulnovo/ITK,jcfr/ITK,fbudin69500/ITK,eile/ITK,wkjeong/ITK,msmolens/ITK,zachary-williamson/ITK,blowekamp/ITK,heimdali/ITK,CapeDrew/DITK,hjmjohnson/ITK,msmolens/ITK,jmerkow/ITK,malaterre/ITK,thewtex/ITK,paulnovo/ITK,PlutoniumHeart/ITK,blowekamp/ITK,CapeDrew/DCMTK-ITK,stnava/ITK,hinerm/ITK,InsightSoftwareConsortium/ITK,eile/ITK,hendradarwin/ITK,msmolens/ITK,LucHermitte/ITK,msmolens/ITK,hendradarwin/ITK,CapeDrew/DITK,spinicist/ITK,thewtex/ITK,jmerkow/ITK,paulnovo/ITK,jmerkow/ITK,CapeDrew/DCMTK-ITK,wkjeong/ITK,LucasGandel/ITK,paulnovo/ITK,biotrump/ITK,malaterre/ITK,vfonov/ITK,LucasGandel/ITK,daviddoria/itkHoughTransform,biotrump/ITK,fedral/ITK,heimdali/ITK,fuentesdt/InsightToolkit-dev,paulnovo/ITK,vfonov/ITK,thewtex/ITK,richardbeare/ITK,ajjl/ITK,jmerkow/ITK,vfonov/ITK,richardbeare/ITK,Kitware/ITK,LucasGandel/ITK,cpatrick/ITK-RemoteIO,rhgong/itk-with-dom,wkjeong/ITK,BRAINSia/ITK,paulnovo/ITK,fedral/ITK,jcfr/ITK,blowekamp/ITK,LucHermitte/ITK,CapeDrew/DCMTK-ITK,eile/ITK,hjmjohnson/ITK,BRAINSia/ITK,itkvideo/ITK,cpatrick/ITK-RemoteIO,GEHC-Surgery/ITK,fbudin69500/ITK,Kitware/ITK,atsnyder/ITK,PlutoniumHeart/ITK,itkvideo/ITK,LucHermitte/ITK,msmolens/ITK,fedral/ITK,hinerm/ITK,PlutoniumHeart/ITK,malaterre/ITK,stnava/ITK,ajjl/ITK,ajjl/ITK,heimdali/ITK,wkjeong/ITK,thewtex/ITK,hinerm/ITK,vfonov/ITK,vfonov/ITK,ajjl/ITK,eile/ITK,PlutoniumHeart/ITK,BRAINSia/ITK,blowekamp/ITK,BlueBrain/ITK,eile/ITK,hinerm/ITK,biotrump/ITK,LucasGandel/ITK,spinicist/ITK,CapeDrew/DITK,cpatrick/ITK-RemoteIO,zachary-williamson/ITK,rhgong/itk-with-dom,wkjeong/ITK,jmerkow/ITK,itkvideo/ITK,CapeDrew/DITK,jcfr/ITK,fuentesdt/InsightToolkit-dev,InsightSoftwareConsortium/ITK,daviddoria/itkHoughTransform,atsnyder/ITK,malaterre/ITK,rhgong/itk-with-dom,msmolens/ITK,ajjl/ITK,LucasGandel/ITK,CapeDrew/DITK,biotrump/ITK,fedral/ITK,rhgong/itk-with-dom,CapeDrew/DCMTK-ITK,eile/ITK,CapeDrew/DCMTK-ITK,CapeDrew/DCMTK-ITK,CapeDrew/DCMTK-ITK,jcfr/ITK,fbudin69500/ITK,fedral/ITK,msmolens/ITK,stnava/ITK
/** * Example on the use of the WatershedImageFilter * */ import InsightToolkit.*; public class WatershedSegmentation1 { public static void main( String argv[] ) { System.out.println("WatershedSegmentation1 Example"); itkImageFileReaderF2_Pointer reader = itkImageFileReaderF2.itkImageFileReaderF2_New(); reader.SetFileName( argv[0] ); itkGradientAnisotropicDiffusionImageFilterF2F2_Pointer diffusion = itkGradientAnisotropicDiffusionImageFilterF2F2.itkGradientAnisotropicDiffusionImageFilterF2F2_New(); diffusion.SetInput( reader.GetOutput() ); diffusion.SetTimeStep( 0.0625 ); diffusion.SetConductanceParameter( 9.0 ); diffusion.SetNumberOfIterations( 5 ); itkGradientMagnitudeImageFilterF2F2_Pointer gradient = itkGradientMagnitudeImageFilterF2F2.itkGradientMagnitudeImageFilterF2F2_New(); gradient.SetInput(diffusion.GetOutput()); itkWatershedImageFilterF2_Pointer watershed = itkWatershedImageFilterF2.itkWatershedImageFilterF2_New(); watershed.SetInput( gradient.GetOutput() ); watershed.SetThreshold( 0.01 ); watershed.SetLevel( 0.2 ); itkImageFileWriterUL2_Pointer writer = itkImageFileWriterUL2.itkImageFileWriterUL2_New(); writer.SetFileName( argv[1] ); writer.SetInput( watershed.GetOutput() ); writer.Update(); } }
Examples/Segmentation/WatershedSegmentation1.java
ENH: Translation of WatershedSegmentation1.py into Java.
Examples/Segmentation/WatershedSegmentation1.java
ENH: Translation of WatershedSegmentation1.py into Java.
<ide><path>xamples/Segmentation/WatershedSegmentation1.java <add>/** <add> * Example on the use of the WatershedImageFilter <add> * <add> */ <add> <add>import InsightToolkit.*; <add> <add>public class WatershedSegmentation1 <add>{ <add> public static void main( String argv[] ) <add> { <add> System.out.println("WatershedSegmentation1 Example"); <add> <add> itkImageFileReaderF2_Pointer reader = itkImageFileReaderF2.itkImageFileReaderF2_New(); <add> reader.SetFileName( argv[0] ); <add> <add> itkGradientAnisotropicDiffusionImageFilterF2F2_Pointer diffusion = <add> itkGradientAnisotropicDiffusionImageFilterF2F2.itkGradientAnisotropicDiffusionImageFilterF2F2_New(); <add> <add> diffusion.SetInput( reader.GetOutput() ); <add> diffusion.SetTimeStep( 0.0625 ); <add> diffusion.SetConductanceParameter( 9.0 ); <add> diffusion.SetNumberOfIterations( 5 ); <add> <add> itkGradientMagnitudeImageFilterF2F2_Pointer gradient = <add> itkGradientMagnitudeImageFilterF2F2.itkGradientMagnitudeImageFilterF2F2_New(); <add> <add> gradient.SetInput(diffusion.GetOutput()); <add> <add> itkWatershedImageFilterF2_Pointer watershed = <add> itkWatershedImageFilterF2.itkWatershedImageFilterF2_New(); <add> <add> watershed.SetInput( gradient.GetOutput() ); <add> watershed.SetThreshold( 0.01 ); <add> watershed.SetLevel( 0.2 ); <add> <add> itkImageFileWriterUL2_Pointer writer = itkImageFileWriterUL2.itkImageFileWriterUL2_New(); <add> writer.SetFileName( argv[1] ); <add> writer.SetInput( watershed.GetOutput() ); <add> writer.Update(); <add> <add> } <add> <add>} <add> <add>
Java
bsd-3-clause
92929e64ba2c27e5298522d0df50ab06e56ea92b
0
cyclus/cyclist2,FlanFlanagan/cyclist2
package edu.utah.sci.cyclist.core.ui.wizards; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyCode; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; import edu.utah.sci.cyclist.Cyclist; public class SaveWsWizard extends VBox { // GUI elements private Stage _dialog; private ObjectProperty<Boolean> _selection = new SimpleObjectProperty<>(); // * * * Constructor creates a new stage * * * // public SaveWsWizard() { createDialog(); } // * * * Show the dialog * * * // public ObjectProperty<Boolean> show(Window window) { _dialog.initOwner (window); _dialog.show(); _dialog.setX(window.getX() + (window.getWidth() - _dialog.getWidth())*0.5); _dialog.setY(window.getY() + (window.getHeight() - _dialog.getHeight())*0.5); return _selection; } // * * * Create the dialog private void createDialog(){ _dialog = new Stage(); _dialog.setTitle("Save WorkSpace"); _dialog.setHeight(100); _dialog.initModality(Modality.WINDOW_MODAL); _dialog.setScene( createScene(_dialog) ); } // * * * Create scene creates the GUI * * * // private Scene createScene(final Stage dialog) { VBox vbox = new VBox(); vbox.setSpacing(10); vbox.setAlignment(Pos.CENTER); Text text = new Text("Workspace has been modified. Save changed? "); text.setFont(new Font(12)); HBox hbox = new HBox(); hbox.setAlignment(Pos.BOTTOM_CENTER); hbox.setSpacing(10); hbox.setPadding(new Insets(5)); hbox.setMinWidth(300); Button yes = new Button("Yes"); // yes.setDefaultButton(true); yes.setMinWidth(50); yes.setAlignment(Pos.CENTER); Button no = new Button("No"); no.setMinWidth(50); no.setAlignment(Pos.CENTER); Button cancel = new Button("Cancel"); cancel.setCancelButton(true); cancel.setMinWidth(50); cancel.setAlignment(Pos.CENTER); hbox.getChildren().addAll(yes,no,cancel); cancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _dialog.hide(); }; }); cancel.setOnKeyPressed((ke)-> { if (ke.getCode() == KeyCode.ENTER) { cancel.fire(); } } ); yes.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _selection.set(true); _dialog.hide(); }; }); yes.setOnKeyPressed((ke)-> {if (ke.getCode() == KeyCode.ENTER) yes.fire(); } ); no.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _selection.set(false); _dialog.hide(); }; }); no.setOnKeyPressed((ke)-> { if (ke.getCode() == KeyCode.ENTER) no.fire(); } ); vbox.getChildren().addAll(text,hbox); // Create the scene Scene scene = new Scene(vbox); scene.getStylesheets().add(Cyclist.class.getResource("assets/Cyclist.css").toExternalForm()); return scene; } }
cyclist/src/edu/utah/sci/cyclist/core/ui/wizards/SaveWsWizard.java
package edu.utah.sci.cyclist.core.ui.wizards; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; import edu.utah.sci.cyclist.Cyclist; public class SaveWsWizard extends VBox { // GUI elements private Stage _dialog; private ObjectProperty<Boolean> _selection = new SimpleObjectProperty<>(); // * * * Constructor creates a new stage * * * // public SaveWsWizard() { createDialog(); } // * * * Show the dialog * * * // public ObjectProperty<Boolean> show(Window window) { _dialog.initOwner (window); _dialog.show(); _dialog.setX(window.getX() + (window.getWidth() - _dialog.getWidth())*0.5); _dialog.setY(window.getY() + (window.getHeight() - _dialog.getHeight())*0.5); return _selection; } // * * * Create the dialog private void createDialog(){ _dialog = new Stage(); _dialog.setTitle("Save WorkSpace"); _dialog.setHeight(100); _dialog.initModality(Modality.WINDOW_MODAL); _dialog.setScene( createScene(_dialog) ); } // * * * Create scene creates the GUI * * * // private Scene createScene(final Stage dialog) { VBox vbox = new VBox(); vbox.setSpacing(10); vbox.setAlignment(Pos.CENTER); Text text = new Text("WorkSpace has been modified. Save changed? "); text.setFont(new Font(12)); HBox hbox = new HBox(); hbox.setAlignment(Pos.BOTTOM_CENTER); hbox.setSpacing(10); hbox.setPadding(new Insets(5)); hbox.setMinWidth(300); Button yes = new Button("Yes"); yes.setMinWidth(50); yes.setAlignment(Pos.CENTER); Button no = new Button("No"); no.setMinWidth(50); no.setAlignment(Pos.CENTER); Button cancel = new Button("Cancel"); cancel.setMinWidth(50); cancel.setAlignment(Pos.CENTER); hbox.getChildren().addAll(yes,no,cancel); cancel.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _dialog.hide(); }; }); yes.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _selection.set(true); _dialog.hide(); }; }); no.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { _selection.set(false); _dialog.hide(); }; }); vbox.getChildren().addAll(text,hbox); // Create the scene Scene scene = new Scene(vbox); scene.getStylesheets().add(Cyclist.class.getResource("assets/Cyclist.css").toExternalForm()); return scene; } }
enable escape/return keys on the save exit panel
cyclist/src/edu/utah/sci/cyclist/core/ui/wizards/SaveWsWizard.java
enable escape/return keys on the save exit panel
<ide><path>yclist/src/edu/utah/sci/cyclist/core/ui/wizards/SaveWsWizard.java <ide> import javafx.geometry.Pos; <ide> import javafx.scene.Scene; <ide> import javafx.scene.control.Button; <add>import javafx.scene.input.KeyCode; <ide> import javafx.scene.layout.HBox; <ide> import javafx.scene.layout.VBox; <ide> import javafx.scene.text.Font; <ide> vbox.setSpacing(10); <ide> vbox.setAlignment(Pos.CENTER); <ide> <del> Text text = new Text("WorkSpace has been modified. Save changed? "); <add> Text text = new Text("Workspace has been modified. Save changed? "); <ide> text.setFont(new Font(12)); <ide> <ide> HBox hbox = new HBox(); <ide> hbox.setMinWidth(300); <ide> <ide> Button yes = new Button("Yes"); <add>// yes.setDefaultButton(true); <ide> yes.setMinWidth(50); <ide> yes.setAlignment(Pos.CENTER); <ide> Button no = new Button("No"); <ide> no.setMinWidth(50); <ide> no.setAlignment(Pos.CENTER); <ide> Button cancel = new Button("Cancel"); <add> cancel.setCancelButton(true); <ide> cancel.setMinWidth(50); <ide> cancel.setAlignment(Pos.CENTER); <ide> hbox.getChildren().addAll(yes,no,cancel); <ide> _dialog.hide(); <ide> }; <ide> }); <add> cancel.setOnKeyPressed((ke)-> { if (ke.getCode() == KeyCode.ENTER) { cancel.fire(); } } ); <add> <ide> yes.setOnAction(new EventHandler<ActionEvent>() { <ide> @Override <ide> public void handle(ActionEvent arg0) { <ide> _dialog.hide(); <ide> }; <ide> }); <add> yes.setOnKeyPressed((ke)-> {if (ke.getCode() == KeyCode.ENTER) yes.fire(); } ); <add> <ide> no.setOnAction(new EventHandler<ActionEvent>() { <ide> @Override <ide> public void handle(ActionEvent arg0) { <ide> _dialog.hide(); <ide> }; <ide> }); <add> no.setOnKeyPressed((ke)-> { if (ke.getCode() == KeyCode.ENTER) no.fire(); } ); <ide> <ide> vbox.getChildren().addAll(text,hbox); <ide>
JavaScript
mit
fa16198885939d54ffb75fd180d9d4cf982bddec
0
adambbecker/generator-abb-static
// ************************** // -- Example jQuery start -- // ************************** // // (function ($, document) { // // // Site definition // window.Site = $.extend({}, window.Site, { // // // ======================================= // // Initialize Site (attach handlers, etc.) // // ======================================= // init: function() { // // } // // }); // // // ======================================= // // Initialize // // ======================================= // Site.init(); // // })(jQuery, document);
app/templates/app.js
Example jQuery site in app.js
app/templates/app.js
Example jQuery site in app.js
<ide><path>pp/templates/app.js <add>// ************************** <add>// -- Example jQuery start -- <add>// ************************** <add>// <add>// (function ($, document) { <add>// <add>// // Site definition <add>// window.Site = $.extend({}, window.Site, { <add>// <add>// // ======================================= <add>// // Initialize Site (attach handlers, etc.) <add>// // ======================================= <add>// init: function() { <add>// <add>// } <add>// <add>// }); <add>// <add>// // ======================================= <add>// // Initialize <add>// // ======================================= <add>// Site.init(); <add>// <add>// })(jQuery, document);
Java
apache-2.0
19c9de0fc235b1a4224485f3bc29db0efaf9ee20
0
stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.persistence; import alpine.resources.AlpineRequest; import alpine.resources.OrderDirection; import alpine.resources.Pagination; import alpine.validation.RegexSequence; import org.datanucleus.api.jdo.JDOQuery; import javax.jdo.PersistenceManager; import javax.jdo.Query; import java.lang.reflect.Field; import java.security.Principal; import java.util.Collection; import java.util.List; import java.util.Map; /** * Base persistence manager that implements AutoCloseable so that the PersistenceManager will * be automatically closed when used in a try-with-resource block. * * @author Steve Springett * @since 1.0.0 */ public abstract class AbstractAlpineQueryManager implements AutoCloseable { protected final Principal principal; protected final Pagination pagination; protected final String filter; protected final String orderBy; protected final OrderDirection orderDirection; protected final PersistenceManager pm = PersistenceManagerFactory.createPersistenceManager(); /** * Default constructor */ public AbstractAlpineQueryManager() { principal = null; pagination = new Pagination(0, 0); filter = null; orderBy = null; orderDirection = OrderDirection.UNSPECIFIED; } /** * Constructs a new QueryManager with the following: * @param principal a Principal, or null * @param pagination a Pagination request, or null * @param filter a String filter, or null * @param orderBy the field to order by * @param orderDirection the sorting direction * @since 1.0.0 */ public AbstractAlpineQueryManager(final Principal principal, final Pagination pagination, final String filter, final String orderBy, final OrderDirection orderDirection) { this.principal = principal; this.pagination = pagination; this.filter = filter; this.orderBy = orderBy; this.orderDirection = orderDirection; } /** * Constructs a new QueryManager. Deconstructs the specified AlpineRequest * into its individual components including pagination and ordering. * @param request an AlpineRequest object * @since 1.0.0 */ public AbstractAlpineQueryManager(final AlpineRequest request) { this.principal = request.getPrincipal(); this.pagination = request.getPagination(); this.filter = request.getFilter(); this.orderBy = request.getOrderBy(); this.orderDirection = request.getOrderDirection(); } /** * Wrapper around {@link Query#execute()} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query) { return decorate(query).execute(); } /** * Wrapper around {@link Query#execute(Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query, final Object p1) { return decorate(query).execute(p1); } /** * Wrapper around {@link Query#execute(Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query, final Object p1, final Object p2) { return decorate(query).execute(p1, p2); } /** * Wrapper around {@link Query#execute(Object, Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query, final Object p1, final Object p2, final Object p3) { return decorate(query).execute(p1, p2, p3); } /** * Wrapper around {@link Query#executeWithArray(Object...)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Object</code> array with all of the parameters * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query, final Object... parameters) { return decorate(query).executeWithArray(parameters); } /** * Wrapper around {@link Query#executeWithMap(Map)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Map</code> containing all of the parameters. * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query, final Map parameters) { return decorate(query).executeWithMap(parameters); } /** * Given a query, this method will decorate that query with pagination, ordering, * and sorting direction. Specific checks are performed to ensure the execution * of the query is capable of being paged and that ordering can be securely performed. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Query decorate(final Query query) { if (pagination != null && pagination.isPaginated()) { final long begin = (pagination.getPage() * pagination.getSize()) - pagination.getSize(); final long end = begin + pagination.getSize(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); for (Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @return the number of items * @since 1.0.0 */ public long getCount(final Query query) { //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); query.setOrdering(null); return (Long) query.execute(); } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param cls the persistence-capable class to query * @return the number of items * @since 1.0.0 */ public long getCount(final Class cls) { final Query query = pm.newQuery(cls); //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); return (Long) query.execute(); } /** * Deletes one or more PersistenceCapable objects. * @param objects an array of one or more objects to delete * @since 1.0.0 */ public void delete(Object... objects) { pm.currentTransaction().begin(); pm.deletePersistentAll(objects); pm.currentTransaction().commit(); } /** * Deletes one or more PersistenceCapable objects. * @param collection a collection of one or more objects to delete * @since 1.0.0 */ public void delete(Collection collection) { pm.currentTransaction().begin(); pm.deletePersistentAll(collection); pm.currentTransaction().commit(); } /** * Retrieves an object by its ID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param id the object id to retrieve * @return an object of the specified type * @since 1.0.0 */ public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { final Query query = pm.newQuery(clazz, "uuid == :uuid"); final List<T> result = (List<T>) query.execute(uuid); return result.size() == 0 ? null : result.get(0); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid, String fetchGroup) { pm.getFetchPlan().addGroup(fetchGroup); return getObjectByUuid(clazz, uuid); } /** * Closes the PersistenceManager instance. * @since 1.0.0 */ public void close() { pm.close(); } /** * Upon finalization, closes the PersistenceManager, if not already closed. * @throws Throwable the {@code Exception} raised by this method * @since 1.0.0 */ protected void finalize() throws Throwable { close(); super.finalize(); } }
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.persistence; import alpine.resources.AlpineRequest; import alpine.resources.OrderDirection; import alpine.resources.Pagination; import alpine.validation.RegexSequence; import org.datanucleus.api.jdo.JDOQuery; import javax.jdo.PersistenceManager; import javax.jdo.Query; import java.lang.reflect.Field; import java.security.Principal; import java.util.Collection; import java.util.List; /** * Base persistence manager that implements AutoCloseable so that the PersistenceManager will * be automatically closed when used in a try-with-resource block. * * @author Steve Springett * @since 1.0.0 */ public abstract class AbstractAlpineQueryManager implements AutoCloseable { protected final Principal principal; protected final Pagination pagination; protected final String filter; protected final String orderBy; protected final OrderDirection orderDirection; protected final PersistenceManager pm = PersistenceManagerFactory.createPersistenceManager(); /** * Default constructor */ public AbstractAlpineQueryManager() { principal = null; pagination = new Pagination(0, 0); filter = null; orderBy = null; orderDirection = OrderDirection.UNSPECIFIED; } /** * Constructs a new QueryManager with the following: * @param principal a Principal, or null * @param pagination a Pagination request, or null * @param filter a String filter, or null * @param orderBy the field to order by * @param orderDirection the sorting direction * @since 1.0.0 */ public AbstractAlpineQueryManager(final Principal principal, final Pagination pagination, final String filter, final String orderBy, final OrderDirection orderDirection) { this.principal = principal; this.pagination = pagination; this.filter = filter; this.orderBy = orderBy; this.orderDirection = orderDirection; } /** * Constructs a new QueryManager. Deconstructs the specified AlpineRequest * into its individual components including pagination and ordering. * @param request an AlpineRequest object * @since 1.0.0 */ public AbstractAlpineQueryManager(final AlpineRequest request) { this.principal = request.getPrincipal(); this.pagination = request.getPagination(); this.filter = request.getFilter(); this.orderBy = request.getOrderBy(); this.orderDirection = request.getOrderDirection(); } /** * Wrapper around {@link Query#execute()} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Object execute(final Query query) { return decorate(query).execute(); } /** * Given a query, this method will decorate that query with pagination, ordering, * and sorting direction. Specific checks are performed to ensure the execution * of the query is capable of being paged and that ordering can be securely performed. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Query decorate(final Query query) { if (pagination != null && pagination.isPaginated()) { long begin = (pagination.getPage() * pagination.getSize()) - pagination.getSize(); long end = begin + pagination.getSize(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; org.datanucleus.store.query.Query iq = ((JDOQuery)query).getInternalQuery(); for (Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @return the number of items * @since 1.0.0 */ public long getCount(final Query query) { //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); query.setOrdering(null); return (Long)query.execute(); } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param cls the persistence-capable class to query * @return the number of items * @since 1.0.0 */ public long getCount(final Class cls) { Query query = pm.newQuery(cls); //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); return (Long)query.execute(); } /** * Deletes one or more PersistenceCapable objects. * @param objects an array of one or more objects to delete * @since 1.0.0 */ public void delete(Object... objects) { pm.currentTransaction().begin(); pm.deletePersistentAll(objects); pm.currentTransaction().commit(); } /** * Deletes one or more PersistenceCapable objects. * @param collection a collection of one or more objects to delete * @since 1.0.0 */ public void delete(Collection collection) { pm.currentTransaction().begin(); pm.deletePersistentAll(collection); pm.currentTransaction().commit(); } /** * Retrieves an object by its ID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param id the object id to retrieve * @return an object of the specified type * @since 1.0.0 */ public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { final Query query = pm.newQuery(clazz, "uuid == :uuid"); final List<T> result = (List<T>) query.execute(uuid); return result.size() == 0 ? null : result.get(0); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid, String fetchGroup) { pm.getFetchPlan().addGroup(fetchGroup); return getObjectByUuid(clazz, uuid); } /** * Closes the PersistenceManager instance. * @since 1.0.0 */ public void close() { pm.close(); } /** * Upon finalization, closes the PersistenceManager, if not already closed. * @throws Throwable the {@code Exception} raised by this method * @since 1.0.0 */ protected void finalize() throws Throwable { close(); super.finalize(); } }
Added additional execute wrapper methods
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
Added additional execute wrapper methods
<ide><path>lpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java <ide> import java.security.Principal; <ide> import java.util.Collection; <ide> import java.util.List; <add>import java.util.Map; <ide> <ide> /** <ide> * Base persistence manager that implements AutoCloseable so that the PersistenceManager will <ide> } <ide> <ide> /** <add> * Wrapper around {@link Query#execute(Object)} that adds transparent support for <add> * pagination and ordering of results via {@link #decorate(Query)}. <add> * @param query the JDO Query object to execute <add> * @param p1 the value of the first parameter declared. <add> * @return a Collection of objects <add> * @since 1.0.0 <add> */ <add> public Object execute(final Query query, final Object p1) { <add> return decorate(query).execute(p1); <add> } <add> <add> /** <add> * Wrapper around {@link Query#execute(Object, Object)} that adds transparent support for <add> * pagination and ordering of results via {@link #decorate(Query)}. <add> * @param query the JDO Query object to execute <add> * @param p1 the value of the first parameter declared. <add> * @param p2 the value of the second parameter declared. <add> * @return a Collection of objects <add> * @since 1.0.0 <add> */ <add> public Object execute(final Query query, final Object p1, final Object p2) { <add> return decorate(query).execute(p1, p2); <add> } <add> <add> /** <add> * Wrapper around {@link Query#execute(Object, Object, Object)} that adds transparent support for <add> * pagination and ordering of results via {@link #decorate(Query)}. <add> * @param query the JDO Query object to execute <add> * @param p1 the value of the first parameter declared. <add> * @param p2 the value of the second parameter declared. <add> * @param p3 the value of the third parameter declared. <add> * @return a Collection of objects <add> * @since 1.0.0 <add> */ <add> public Object execute(final Query query, final Object p1, final Object p2, final Object p3) { <add> return decorate(query).execute(p1, p2, p3); <add> } <add> <add> /** <add> * Wrapper around {@link Query#executeWithArray(Object...)} that adds transparent support for <add> * pagination and ordering of results via {@link #decorate(Query)}. <add> * @param query the JDO Query object to execute <add> * @param parameters the <code>Object</code> array with all of the parameters <add> * @return a Collection of objects <add> * @since 1.0.0 <add> */ <add> public Object execute(final Query query, final Object... parameters) { <add> return decorate(query).executeWithArray(parameters); <add> } <add> <add> /** <add> * Wrapper around {@link Query#executeWithMap(Map)} that adds transparent support for <add> * pagination and ordering of results via {@link #decorate(Query)}. <add> * @param query the JDO Query object to execute <add> * @param parameters the <code>Map</code> containing all of the parameters. <add> * @return a Collection of objects <add> * @since 1.0.0 <add> */ <add> public Object execute(final Query query, final Map parameters) { <add> return decorate(query).executeWithMap(parameters); <add> } <add> <add> /** <ide> * Given a query, this method will decorate that query with pagination, ordering, <ide> * and sorting direction. Specific checks are performed to ensure the execution <ide> * of the query is capable of being paged and that ordering can be securely performed. <ide> */ <ide> public Query decorate(final Query query) { <ide> if (pagination != null && pagination.isPaginated()) { <del> long begin = (pagination.getPage() * pagination.getSize()) - pagination.getSize(); <del> long end = begin + pagination.getSize(); <add> final long begin = (pagination.getPage() * pagination.getSize()) - pagination.getSize(); <add> final long end = begin + pagination.getSize(); <ide> query.setRange(begin, end); <ide> } <ide> if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { <ide> // Check to see if the specified orderBy field is defined in the class being queried. <ide> boolean found = false; <del> org.datanucleus.store.query.Query iq = ((JDOQuery)query).getInternalQuery(); <add> final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); <ide> for (Field field: iq.getCandidateClass().getDeclaredFields()) { <ide> if (orderBy.equals(field.getName())) { <ide> found = true; <ide> //query.addExtension("datanucleus.query.resultSizeMethod", "count"); <ide> query.setResult("count(id)"); <ide> query.setOrdering(null); <del> return (Long)query.execute(); <add> return (Long) query.execute(); <ide> } <ide> <ide> /** <ide> * @since 1.0.0 <ide> */ <ide> public long getCount(final Class cls) { <del> Query query = pm.newQuery(cls); <add> final Query query = pm.newQuery(cls); <ide> //query.addExtension("datanucleus.query.resultSizeMethod", "count"); <ide> query.setResult("count(id)"); <del> return (Long)query.execute(); <add> return (Long) query.execute(); <ide> } <ide> <ide> /**
JavaScript
mit
9bbfc491083424ba2614bbe5af13a7e750c80d77
0
staltz/mvi-example
;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // // The shims in this file are not fully implemented shims for the ES5 // features, but do work for the particular usecases there is in // the other modules. // var toString = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; // Array.isArray is supported in IE9 function isArray(xs) { return toString.call(xs) === '[object Array]'; } exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; // Array.prototype.indexOf is supported in IE9 exports.indexOf = function indexOf(xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (x === xs[i]) return i; } return -1; }; // Array.prototype.filter is supported in IE9 exports.filter = function filter(xs, fn) { if (xs.filter) return xs.filter(fn); var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; }; // Array.prototype.forEach is supported in IE9 exports.forEach = function forEach(xs, fn, self) { if (xs.forEach) return xs.forEach(fn, self); for (var i = 0; i < xs.length; i++) { fn.call(self, xs[i], i, xs); } }; // Array.prototype.map is supported in IE9 exports.map = function map(xs, fn) { if (xs.map) return xs.map(fn); var out = new Array(xs.length); for (var i = 0; i < xs.length; i++) { out[i] = fn(xs[i], i, xs); } return out; }; // Array.prototype.reduce is supported in IE9 exports.reduce = function reduce(array, callback, opt_initialValue) { if (array.reduce) return array.reduce(callback, opt_initialValue); var value, isValueSet = false; if (2 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (var i = 0, l = array.length; l > i; ++i) { if (array.hasOwnProperty(i)) { if (isValueSet) { value = callback(value, array[i], i, array); } else { value = array[i]; isValueSet = true; } } } return value; }; // String.prototype.substr - negative index don't work in IE8 if ('ab'.substr(-1) !== 'b') { exports.substr = function (str, start, length) { // did we get a negative start, calculate how much it is from the beginning of the string if (start < 0) start = str.length + start; // call the original function return str.substr(start, length); }; } else { exports.substr = function (str, start, length) { return str.substr(start, length); }; } // String.prototype.trim is supported in IE9 exports.trim = function (str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); }; // Function.prototype.bind is supported in IE9 exports.bind = function () { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); if (fn.bind) return fn.bind.apply(fn, args); var self = args.shift(); return function () { fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); }; }; // Object.create is supported in IE9 function create(prototype, properties) { var object; if (prototype === null) { object = { '__proto__' : null }; } else { if (typeof prototype !== 'object') { throw new TypeError( 'typeof prototype[' + (typeof prototype) + '] != \'object\'' ); } var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (typeof properties !== 'undefined' && Object.defineProperties) { Object.defineProperties(object, properties); } return object; } exports.create = typeof Object.create === 'function' ? Object.create : create; // Object.keys and Object.getOwnPropertyNames is supported in IE9 however // they do show a description and number property on Error objects function notObject(object) { return ((typeof object != "object" && typeof object != "function") || object === null); } function keysShim(object) { if (notObject(object)) { throw new TypeError("Object.keys called on a non-object"); } var result = []; for (var name in object) { if (hasOwnProperty.call(object, name)) { result.push(name); } } return result; } // getOwnPropertyNames is almost the same as Object.keys one key feature // is that it returns hidden properties, since that can't be implemented, // this feature gets reduced so it just shows the length property on arrays function propertyShim(object) { if (notObject(object)) { throw new TypeError("Object.getOwnPropertyNames called on a non-object"); } var result = keysShim(object); if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { result.push('length'); } return result; } var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? Object.getOwnPropertyNames : propertyShim; if (new Error().hasOwnProperty('description')) { var ERROR_PROPERTY_FILTER = function (obj, array) { if (toString.call(obj) === '[object Error]') { array = exports.filter(array, function (name) { return name !== 'description' && name !== 'number' && name !== 'message'; }); } return array; }; exports.keys = function (object) { return ERROR_PROPERTY_FILTER(object, keys(object)); }; exports.getOwnPropertyNames = function (object) { return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); }; } else { exports.keys = keys; exports.getOwnPropertyNames = getOwnPropertyNames; } // Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements function valueObject(value, key) { return { value: value[key] }; } if (typeof Object.getOwnPropertyDescriptor === 'function') { try { Object.getOwnPropertyDescriptor({'a': 1}, 'a'); exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; } catch (e) { // IE8 dom element issue - use a try catch and default to valueObject exports.getOwnPropertyDescriptor = function (value, key) { try { return Object.getOwnPropertyDescriptor(value, key); } catch (e) { return valueObject(value, key); } }; } } else { exports.getOwnPropertyDescriptor = valueObject; } },{}],2:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!util.isNumber(n) || n < 0) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (util.isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (util.isUndefined(handler)) return false; if (util.isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (util.isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, util.isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (util.isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (util.isObject(this._events[type]) && !this._events[type].warned) { var m; if (!util.isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!util.isFunction(listener)) throw TypeError('listener must be a function'); function g() { this.removeListener(type, g); listener.apply(this, arguments); } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (util.isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (util.isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (util.isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (util.isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (util.isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; },{"util":3}],3:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var shims = require('_shims'); var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; shims.forEach(array, function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = shims.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = shims.getOwnPropertyNames(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } shims.forEach(keys, function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (shims.indexOf(ctx.seen, desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = shims.reduce(output, function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return shims.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && objectToString(e) === '[object Error]'; } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.binarySlice === 'function' ; } exports.isBuffer = isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = shims.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = shims.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } },{"_shims":1}],4:[function(require,module,exports){ },{}],5:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],6:[function(require,module,exports){ var DataSet = require("data-set") module.exports = addEvent function addEvent(target, type, handler) { var ds = DataSet(target) var events = ds[type] if (!events) { ds[type] = handler } else if (Array.isArray(events)) { if (events.indexOf(handler) === -1) { events.push(handler) } } else if (events !== handler) { ds[type] = [events, handler] } } },{"data-set":11}],7:[function(require,module,exports){ var globalDocument = require("global/document") var DataSet = require("data-set") var addEvent = require("./add-event.js") var removeEvent = require("./remove-event.js") var ProxyEvent = require("./proxy-event.js") module.exports = DOMDelegator function DOMDelegator(document) { document = document || globalDocument this.target = document.documentElement this.events = {} this.rawEventListeners = {} this.globalListeners = {} } DOMDelegator.prototype.addEventListener = addEvent DOMDelegator.prototype.removeEventListener = removeEvent DOMDelegator.prototype.addGlobalEventListener = function addGlobalEventListener(eventName, fn) { var listeners = this.globalListeners[eventName] if (!listeners) { listeners = this.globalListeners[eventName] = [] } if (listeners.indexOf(fn) === -1) { listeners.push(fn) } } DOMDelegator.prototype.removeGlobalEventListener = function removeGlobalEventListener(eventName, fn) { var listeners = this.globalListeners[eventName] if (!listeners) { return } var index = listeners.indexOf(fn) if (index !== -1) { listeners.splice(index, 1) } } DOMDelegator.prototype.listenTo = function listenTo(eventName) { if (this.events[eventName]) { return } this.events[eventName] = true listen(this, eventName) } DOMDelegator.prototype.unlistenTo = function unlistenTo(eventName) { if (!this.events[eventName]) { return } this.events[eventName] = false unlisten(this, eventName) } function listen(delegator, eventName) { var listener = delegator.rawEventListeners[eventName] if (!listener) { listener = delegator.rawEventListeners[eventName] = createHandler(eventName, delegator.globalListeners) } delegator.target.addEventListener(eventName, listener, true) } function unlisten(delegator, eventName) { var listener = delegator.rawEventListeners[eventName] if (!listener) { throw new Error("dom-delegator#unlistenTo: cannot " + "unlisten to " + eventName) } delegator.target.removeEventListener(eventName, listener, true) } function createHandler(eventName, globalListeners) { return handler function handler(ev) { var globalHandlers = globalListeners[eventName] || [] var listener = getListener(ev.target, eventName) var handlers = globalHandlers .concat(listener ? listener.handlers : []) if (handlers.length === 0) { return } var arg = new ProxyEvent(ev, listener) handlers.forEach(function (handler) { typeof handler === "function" ? handler(arg) : handler.handleEvent(arg) }) } } function getListener(target, type) { // terminate recursion if parent is `null` if (target === null) { return null } var ds = DataSet(target) // fetch list of handler fns for this event var handler = ds[type] var allHandler = ds.event if (!handler && !allHandler) { return getListener(target.parentNode, type) } var handlers = [].concat(handler || [], allHandler || []) return new Listener(target, handlers) } function Listener(target, handlers) { this.currentTarget = target this.handlers = handlers } },{"./add-event.js":6,"./proxy-event.js":17,"./remove-event.js":18,"data-set":11,"global/document":14}],8:[function(require,module,exports){ var Individual = require("individual") var cuid = require("cuid") var globalDocument = require("global/document") var DOMDelegator = require("./dom-delegator.js") var delegatorCache = Individual("__DOM_DELEGATOR_CACHE@9", { delegators: {} }) var commonEvents = [ "blur", "change", "click", "contextmenu", "dblclick", "error","focus", "focusin", "focusout", "input", "keydown", "keypress", "keyup", "load", "mousedown", "mouseup", "resize", "scroll", "select", "submit", "touchcancel", "touchend", "touchstart", "unload" ] /* Delegator is a thin wrapper around a singleton `DOMDelegator` instance. Only one DOMDelegator should exist because we do not want duplicate event listeners bound to the DOM. `Delegator` will also `listenTo()` all events unless every caller opts out of it */ module.exports = Delegator function Delegator(opts) { opts = opts || {} var document = opts.document || globalDocument var cacheKey = document["__DOM_DELEGATOR_CACHE_TOKEN@9"] if (!cacheKey) { cacheKey = document["__DOM_DELEGATOR_CACHE_TOKEN@9"] = cuid() } var delegator = delegatorCache.delegators[cacheKey] if (!delegator) { delegator = delegatorCache.delegators[cacheKey] = new DOMDelegator(document) } if (opts.defaultEvents !== false) { for (var i = 0; i < commonEvents.length; i++) { delegator.listenTo(commonEvents[i]) } } return delegator } },{"./dom-delegator.js":7,"cuid":9,"global/document":14,"individual":15}],9:[function(require,module,exports){ /** * cuid.js * Collision-resistant UID generator for browsers and node. * Sequential for fast db lookups and recency sorting. * Safe for element IDs and server-side lookups. * * Extracted from CLCTR * * Copyright (c) Eric Elliott 2012 * MIT License */ /*global window, navigator, document, require, process, module */ (function (app) { 'use strict'; var namespace = 'cuid', c = 0, blockSize = 4, base = 36, discreteValues = Math.pow(base, blockSize), pad = function pad(num, size) { var s = "000000000" + num; return s.substr(s.length-size); }, randomBlock = function randomBlock() { return pad((Math.random() * discreteValues << 0) .toString(base), blockSize); }, safeCounter = function () { c = (c < discreteValues) ? c : 0; c++; // this is not subliminal return c - 1; }, api = function cuid() { // Starting with a lowercase letter makes // it HTML element ID friendly. var letter = 'c', // hard-coded allows for sequential access // timestamp // warning: this exposes the exact date and time // that the uid was created. timestamp = (new Date().getTime()).toString(base), // Prevent same-machine collisions. counter, // A few chars to generate distinct ids for different // clients (so different computers are far less // likely to generate the same id) fingerprint = api.fingerprint(), // Grab some more chars from Math.random() random = randomBlock() + randomBlock(); counter = pad(safeCounter().toString(base), blockSize); return (letter + timestamp + counter + fingerprint + random); }; api.slug = function slug() { var date = new Date().getTime().toString(36), counter, print = api.fingerprint().slice(0,1) + api.fingerprint().slice(-1), random = randomBlock().slice(-2); counter = safeCounter().toString(36).slice(-4); return date.slice(-2) + counter + print + random; }; api.globalCount = function globalCount() { // We want to cache the results of this var cache = (function calc() { var i, count = 0; for (i in window) { count++; } return count; }()); api.globalCount = function () { return cache; }; return cache; }; api.fingerprint = function browserPrint() { return pad((navigator.mimeTypes.length + navigator.userAgent.length).toString(36) + api.globalCount().toString(36), 4); }; // don't change anything from here down. if (app.register) { app.register(namespace, api); } else if (typeof module !== 'undefined') { module.exports = api; } else { app[namespace] = api; } }(this.applitude || this)); },{}],10:[function(require,module,exports){ module.exports = createHash function createHash(elem) { var attributes = elem.attributes var hash = {} if (attributes === null || attributes === undefined) { return hash } for (var i = 0; i < attributes.length; i++) { var attr = attributes[i] if (attr.name.substr(0,5) !== "data-") { continue } hash[attr.name.substr(5)] = attr.value } return hash } },{}],11:[function(require,module,exports){ var createStore = require("weakmap-shim/create-store") var Individual = require("individual") var createHash = require("./create-hash.js") var hashStore = Individual("__DATA_SET_WEAKMAP@3", createStore()) module.exports = DataSet function DataSet(elem) { var store = hashStore(elem) if (!store.hash) { store.hash = createHash(elem) } return store.hash } },{"./create-hash.js":10,"individual":15,"weakmap-shim/create-store":12}],12:[function(require,module,exports){ var hiddenStore = require('./hidden-store.js'); module.exports = createStore; function createStore() { var key = {}; return function (obj) { if (typeof obj !== 'object' || obj === null) { throw new Error('Weakmap-shim: Key must be object') } var store = obj.valueOf(key); return store && store.identity === key ? store : hiddenStore(obj, key); }; } },{"./hidden-store.js":13}],13:[function(require,module,exports){ module.exports = hiddenStore; function hiddenStore(obj, key) { var store = { identity: key }; var valueOf = obj.valueOf; Object.defineProperty(obj, "valueOf", { value: function (value) { return value !== key ? valueOf.apply(this, arguments) : store; }, writable: true }); return store; } },{}],14:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = require('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } },{"min-document":4}],15:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};var root = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; module.exports = Individual function Individual(key, value) { if (root[key]) { return root[key] } Object.defineProperty(root, key, { value: value , configurable: true }) return value } },{}],16:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],17:[function(require,module,exports){ var inherits = require("inherits") var ALL_PROPS = [ "altKey", "bubbles", "cancelable", "ctrlKey", "eventPhase", "metaKey", "relatedTarget", "shiftKey", "target", "timeStamp", "type", "view", "which" ] var KEY_PROPS = ["char", "charCode", "key", "keyCode"] var MOUSE_PROPS = [ "button", "buttons", "clientX", "clientY", "layerX", "layerY", "offsetX", "offsetY", "pageX", "pageY", "screenX", "screenY", "toElement" ] var rkeyEvent = /^key|input/ var rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/ module.exports = ProxyEvent function ProxyEvent(ev, listener) { if (!(this instanceof ProxyEvent)) { return new ProxyEvent(ev, listener) } if (rkeyEvent.test(ev.type)) { return new KeyEvent(ev, listener) } else if (rmouseEvent.test(ev.type)) { return new MouseEvent(ev, listener) } for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } ProxyEvent.prototype.preventDefault = function () { this._rawEvent.preventDefault() } function MouseEvent(ev, listener) { for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } for (var j = 0; j < MOUSE_PROPS.length; j++) { var mousePropKey = MOUSE_PROPS[j] this[mousePropKey] = ev[mousePropKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } inherits(MouseEvent, ProxyEvent) function KeyEvent(ev, listener) { for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } for (var j = 0; j < KEY_PROPS.length; j++) { var keyPropKey = KEY_PROPS[j] this[keyPropKey] = ev[keyPropKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } inherits(KeyEvent, ProxyEvent) },{"inherits":16}],18:[function(require,module,exports){ var DataSet = require("data-set") module.exports = removeEvent function removeEvent(target, type, handler) { var ds = DataSet(target) var events = ds[type] if (!events) { return } else if (Array.isArray(events)) { var index = events.indexOf(handler) if (index !== -1) { events.splice(index, 1) } } else if (events === handler) { ds[type] = null } } },{"data-set":11}],19:[function(require,module,exports){ 'use strict'; /* * ItemsIntent. Interprets raw user input and outputs model-friendly user * intents. */ var Rx = require('rx'); var replicate = require('mvi-example/utils/replicate'); var inputAddOneClicks$ = new Rx.Subject(); var inputAddManyClicks$ = new Rx.Subject(); var inputRemoveClicks$ = new Rx.Subject(); var inputItemColorChanged$ = new Rx.Subject(); var inputItemWidthChanged$ = new Rx.Subject(); function observe(ItemsView) { replicate(ItemsView.addOneClicks$, inputAddOneClicks$); replicate(ItemsView.addManyClicks$, inputAddManyClicks$); replicate(ItemsView.removeClicks$, inputRemoveClicks$); replicate(ItemsView.itemColorChanged$, inputItemColorChanged$); replicate(ItemsView.itemWidthChanged$, inputItemWidthChanged$); } var addItem$ = Rx.Observable .merge( inputAddOneClicks$.map(function () { return {operation: 'add', amount: 1}; }), inputAddManyClicks$.map(function () { return {operation: 'add', amount: 1000}; }) ); var removeItem$ = inputRemoveClicks$ .map(function (clickEvent) { return { operation: 'remove', id: Number(clickEvent.currentTarget.attributes['data-item-id'].value) }; }); var colorChanged$ = inputItemColorChanged$ .map(function (inputEvent) { return { operation: 'changeColor', id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), color: inputEvent.currentTarget.value }; }); var widthChanged$ = inputItemWidthChanged$ .map(function (inputEvent) { return { operation: 'changeWidth', id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), width: Number(inputEvent.currentTarget.value) }; }); module.exports = { observe: observe, addItem$: addItem$, removeItem$: removeItem$, colorChanged$: colorChanged$, widthChanged$: widthChanged$ }; },{"mvi-example/utils/replicate":23,"rx":27}],20:[function(require,module,exports){ 'use strict'; /* * ItemsModel. * As output, Observable of array of item data. * As input, ItemsIntent. */ var Rx = require('rx'); var replicate = require('mvi-example/utils/replicate'); var intentAddItem$ = new Rx.Subject(); var intentRemoveItem$ = new Rx.Subject(); var intentWidthChanged$ = new Rx.Subject(); var intentColorChanged$ = new Rx.Subject(); function observe(ItemsIntent) { replicate(ItemsIntent.addItem$, intentAddItem$); replicate(ItemsIntent.removeItem$, intentRemoveItem$); replicate(ItemsIntent.widthChanged$, intentWidthChanged$); replicate(ItemsIntent.colorChanged$, intentColorChanged$); } function createRandomItem() { var hexColor = Math.floor(Math.random() * 16777215).toString(16); while (hexColor.length < 6) { hexColor = '0' + hexColor; } hexColor = '#' + hexColor; var randomWidth = Math.floor(Math.random() * 800 + 200); return {color: hexColor, width: randomWidth}; } function reassignId(item, index) { return {id: index, color: item.color, width: item.width}; } var items$ = Rx.Observable.just([{id: 0, color: 'red', width: 300}]) .merge(intentAddItem$) .merge(intentRemoveItem$) .merge(intentColorChanged$) .merge(intentWidthChanged$) .scan(function (listItems, x) { if (Array.isArray(x)) { return x; } else if (x.operation === 'add') { var newItems = []; for (var i = 0; i < x.amount; i++) { newItems.push(createRandomItem()); } return listItems.concat(newItems).map(reassignId); } else if (x.operation === 'remove') { return listItems .filter(function (item) { return item.id !== x.id; }) .map(reassignId); } else if (x.operation === 'changeColor') { listItems[x.id].color = x.color; return listItems; } else if (x.operation === 'changeWidth') { listItems[x.id].width = x.width; return listItems; } else { return listItems; } }); module.exports = { observe: observe, items$: items$ }; },{"mvi-example/utils/replicate":23,"rx":27}],21:[function(require,module,exports){ 'use strict'; /* * Renderer component. * Subscribes to vtree observables of all view components * and renders them as real DOM elements to the browser. */ var h = require('virtual-hyperscript'); var VDOM = { createElement: require('virtual-dom/create-element'), diff: require('virtual-dom/diff'), patch: require('virtual-dom/patch') }; var DOMDelegator = require('dom-delegator'); var ItemsView = require('mvi-example/views/items'); var delegator; function renderVTreeStream(vtree$, containerSelector) { // Find and prepare the container var container = window.document.querySelector(containerSelector); if (container === null) { console.error('Couldn\'t render into unknown \'' + containerSelector + '\''); return false; } container.innerHTML = ''; // Make the DOM node bound to the VDOM node var rootNode = window.document.createElement('div'); container.appendChild(rootNode); vtree$.startWith(h()) .bufferWithCount(2, 1) .subscribe(function (buffer) { try { var oldVTree = buffer[0]; var newVTree = buffer[1]; rootNode = VDOM.patch(rootNode, VDOM.diff(oldVTree, newVTree)); } catch (err) { console.error(err); } }); return true; } function init() { delegator = new DOMDelegator(); renderVTreeStream(ItemsView.vtree$, '.js-container'); } module.exports = { init: init }; },{"dom-delegator":8,"mvi-example/views/items":24,"virtual-dom/create-element":28,"virtual-dom/diff":29,"virtual-dom/patch":48,"virtual-hyperscript":52}],22:[function(require,module,exports){ 'use strict'; /* * Important Model-View-Intent binding function. */ module.exports = function (model, view, intent) { if (view) { view.observe(model); } if (intent) { intent.observe(view); } if (model) { model.observe(intent); } }; },{}],23:[function(require,module,exports){ 'use strict'; /* * Utility functions */ /** * Forwards all notifications from the source observable to the given subject. * * @param {Rx.Observable} source the origin observable * @param {Rx.Subject} subject the destination subject * @return {Rx.Disposable} a disposable generated by a subscribe method */ function replicate(source, subject) { if (typeof source === 'undefined') { throw new Error('Cannot replicate() if source is undefined.'); } return source.subscribe( function replicationOnNext(x) { subject.onNext(x); }, function replicationOnError(err) { console.error(err); } ); } module.exports = replicate; },{}],24:[function(require,module,exports){ 'use strict'; /* * ItemsView. * As output, Observable of vtree (Virtual DOM tree). * As input, ItemsModel. */ var Rx = require('rx'); var h = require('virtual-hyperscript'); var replicate = require('mvi-example/utils/replicate'); var modelItems$ = new Rx.BehaviorSubject(null); var itemWidthChanged$ = new Rx.Subject(); var itemColorChanged$ = new Rx.Subject(); var removeClicks$ = new Rx.Subject(); var addOneClicks$ = new Rx.Subject(); var addManyClicks$ = new Rx.Subject(); function observe(ItemsModel) { replicate(ItemsModel.items$, modelItems$); } function vrenderTopButtons() { return h('div.topButtons', {}, [ h('button', {'ev-click': function (ev) { addOneClicks$.onNext(ev); }}, 'Add New Item' ), h('button', {'ev-click': function (ev) { addManyClicks$.onNext(ev); }}, 'Add Many Items' ) ]); } function vrenderItem(itemData) { return h('div', { style: { 'border': '1px solid #000', 'background': 'none repeat scroll 0% 0% ' + itemData.color, 'width': itemData.width + 'px', 'height': '70px', 'display': 'block', 'padding': '20px', 'margin': '10px 0px' }}, [ h('input', { type: 'text', value: itemData.color, 'attributes': {'data-item-id': itemData.id}, 'ev-input': function (ev) { itemColorChanged$.onNext(ev); } }), h('div', [ h('input', { type: 'range', min:'200', max:'1000', value: itemData.width, 'attributes': {'data-item-id': itemData.id}, 'ev-input': function (ev) { itemWidthChanged$.onNext(ev); } }) ]), h('div', String(itemData.width)), h('button', { 'attributes': {'data-item-id': itemData.id}, 'ev-click': function (ev) { removeClicks$.onNext(ev); } }, 'Remove') ] ); } var vtree$ = modelItems$ .map(function (itemsData) { return h('div.everything', {}, [ vrenderTopButtons(), itemsData.map(vrenderItem) ]); }); module.exports = { observe: observe, vtree$: vtree$, removeClicks$: removeClicks$, addOneClicks$: addOneClicks$, addManyClicks$: addManyClicks$, itemColorChanged$: itemColorChanged$, itemWidthChanged$: itemWidthChanged$ }; },{"mvi-example/utils/replicate":23,"rx":27,"virtual-hyperscript":52}],25:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >=0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value from the given index. */ observableProto.contains = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (observer) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { observer.onNext(false); observer.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { observer.onNext(true); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { observer.onNext(-1); observer.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { observer.onNext(i); observer.onCompleted(); } i++; }, observer.onError.bind(observer), function () { observer.onNext(-1); observer.onCompleted(); }); }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { count < len && (equal = comparer(value, second[count++])); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; if (!!root.Set) { /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { var source = this; return new AnonymousObservable(function (observer) { var s = new root.Set(); return source.subscribe( s.add.bind(s), observer.onError.bind(observer), function () { observer.onNext(s); observer.onCompleted(); }); }); }; } if (!!root.Map) { /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { observer.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { observer.onError(e); return; } } m.set(key, element); }, observer.onError.bind(observer), function () { observer.onNext(m); observer.onCompleted(); }); }); }; } var fnString = 'function'; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res){ if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThink(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn){ promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && obj.prototype.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj.throw === fnString; } function isObject(val) { return val && val.constructor === Object; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fan; if (isGenFun) { var args = slice.call(arguments), len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : error; gen = fn.apply(this, args); } else { done = done || error; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) res = slice.call(arguments, 1); if (err) { try { ret = gen.throw(err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function(){ if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; /** * Takes a function with a callback and turns it into a thunk. * @param {Function} A function with a callback such as fs.readFile * @returns {Function} A function, when executed will continue the state machine. */ Rx.denodify = function (fn) { return function (){ var args = slice.call(arguments), results, called, callback; args.push(function(){ results = arguments; if (callback && !called) { called = true; cb.apply(this, results); } }); fn.apply(this, args); return function (fn){ callback = fn; if (results && !called) { called = true; fn.apply(this, results); } } } }; /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch(exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( observer.onNext.bind(observer), function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); observer.onError(err); }, observer.onCompleted.bind(observer) ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && observer.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(observer); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this)); },{"__browserify_process":5}],26:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx.virtualtime', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx.all')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // Defaults var Observer = Rx.Observer, Observable = Rx.Observable, Notification = Rx.Notification, VirtualTimeScheduler = Rx.VirtualTimeScheduler, Disposable = Rx.Disposable, disposableEmpty = Disposable.empty, disposableCreate = Disposable.create, CompositeDisposable = Rx.CompositeDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, slice = Array.prototype.slice, inherits = Rx.internals.inherits, defaultComparer = Rx.internals.isEqual; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } function OnNextPredicate(predicate) { this.predicate = predicate; }; OnNextPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'N') { return false; } return this.predicate(other.value); }; function OnErrorPredicate(predicate) { this.predicate = predicate; }; OnErrorPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'E') { return false; } return this.predicate(other.exception); }; var ReactiveTest = Rx.ReactiveTest = { /** Default virtual time used for creation of observable sequences in unit tests. */ created: 100, /** Default virtual time used to subscribe to observable sequences in unit tests. */ subscribed: 200, /** Default virtual time used to dispose subscriptions in unit tests. */ disposed: 1000, /** * Factory method for an OnNext notification record at a given time with a given value or a predicate function. * * 1 - ReactiveTest.onNext(200, 42); * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; }); * * @param ticks Recorded virtual time the OnNext notification occurs. * @param value Recorded value stored in the OnNext notification or a predicate. * @return Recorded OnNext notification. */ onNext: function (ticks, value) { if (typeof value === 'function') { return new Recorded(ticks, new OnNextPredicate(value)); } return new Recorded(ticks, Notification.createOnNext(value)); }, /** * Factory method for an OnError notification record at a given time with a given error. * * 1 - ReactiveTest.onNext(200, new Error('error')); * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; }); * * @param ticks Recorded virtual time the OnError notification occurs. * @param exception Recorded exception stored in the OnError notification. * @return Recorded OnError notification. */ onError: function (ticks, exception) { if (typeof exception === 'function') { return new Recorded(ticks, new OnErrorPredicate(exception)); } return new Recorded(ticks, Notification.createOnError(exception)); }, /** * Factory method for an OnCompleted notification record at a given time. * * @param ticks Recorded virtual time the OnCompleted notification occurs. * @return Recorded OnCompleted notification. */ onCompleted: function (ticks) { return new Recorded(ticks, Notification.createOnCompleted()); }, /** * Factory method for a subscription record based on a given subscription and disposal time. * * @param start Virtual time indicating when the subscription was created. * @param end Virtual time indicating when the subscription was disposed. * @return Subscription object. */ subscribe: function (start, end) { return new Subscription(start, end); } }; /** * Creates a new object recording the production of the specified value at the given virtual time. * * @constructor * @param {Number} time Virtual time the value was produced on. * @param {Mixed} value Value that was produced. * @param {Function} comparer An optional comparer. */ var Recorded = Rx.Recorded = function (time, value, comparer) { this.time = time; this.value = value; this.comparer = comparer || defaultComparer; }; /** * Checks whether the given recorded object is equal to the current instance. * * @param {Recorded} other Recorded object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Recorded.prototype.equals = function (other) { return this.time === other.time && this.comparer(this.value, other.value); }; /** * Returns a string representation of the current Recorded value. * * @returns {String} String representation of the current Recorded value. */ Recorded.prototype.toString = function () { return this.value.toString() + '@' + this.time; }; /** * Creates a new subscription object with the given virtual subscription and unsubscription time. * * @constructor * @param {Number} subscribe Virtual time at which the subscription occurred. * @param {Number} unsubscribe Virtual time at which the unsubscription occurred. */ var Subscription = Rx.Subscription = function (start, end) { this.subscribe = start; this.unsubscribe = end || Number.MAX_VALUE; }; /** * Checks whether the given subscription is equal to the current instance. * @param other Subscription object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Subscription.prototype.equals = function (other) { return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe; }; /** * Returns a string representation of the current Subscription value. * @returns {String} String representation of the current Subscription value. */ Subscription.prototype.toString = function () { return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')'; }; /** @private */ var MockDisposable = Rx.MockDisposable = function (scheduler) { this.scheduler = scheduler; this.disposes = []; this.disposes.push(this.scheduler.clock); }; /* * @memberOf MockDisposable# * @prviate */ MockDisposable.prototype.dispose = function () { this.disposes.push(this.scheduler.clock); }; /** @private */ var MockObserver = (function (_super) { inherits(MockObserver, _super); /* * @constructor * @prviate */ function MockObserver(scheduler) { _super.call(this); this.scheduler = scheduler; this.messages = []; } var MockObserverPrototype = MockObserver.prototype; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onNext = function (value) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); }; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onError = function (exception) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception))); }; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onCompleted = function () { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); }; return MockObserver; })(Observer); /** @private */ var HotObservable = (function (_super) { function subscribe(observer) { var observable = this; this.observers.push(observer); this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; return disposableCreate(function () { var idx = observable.observers.indexOf(observer); observable.observers.splice(idx, 1); observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); }); } inherits(HotObservable, _super); /** * @private * @constructor */ function HotObservable(scheduler, messages) { _super.call(this, subscribe); var message, notification, observable = this; this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; this.observers = []; for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { scheduler.scheduleAbsoluteWithState(null, message.time, function () { var obs = observable.observers.slice(0); for (var j = 0, jLen = obs.length; j < jLen; j++) { innerNotification.accept(obs[j]); } return disposableEmpty; }); })(notification); } } return HotObservable; })(Observable); /** @private */ var ColdObservable = (function (_super) { function subscribe(observer) { var message, notification, observable = this; this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; var d = new CompositeDisposable(); for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { d.add(observable.scheduler.scheduleRelativeWithState(null, message.time, function () { innerNotification.accept(observer); return disposableEmpty; })); })(notification); } return disposableCreate(function () { observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); d.dispose(); }); } inherits(ColdObservable, _super); /** * @private * @constructor */ function ColdObservable(scheduler, messages) { _super.call(this, subscribe); this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; } return ColdObservable; })(Observable); /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */ Rx.TestScheduler = (function (_super) { inherits(TestScheduler, _super); function baseComparer(x, y) { return x > y ? 1 : (x < y ? -1 : 0); } /** @constructor */ function TestScheduler() { _super.call(this, 0, baseComparer); } /** * Schedules an action to be executed at the specified virtual time. * * @param state State passed to the action to be executed. * @param dueTime Absolute virtual time at which to execute the action. * @param action Action to be executed. * @return Disposable object used to cancel the scheduled action (best effort). */ TestScheduler.prototype.scheduleAbsoluteWithState = function (state, dueTime, action) { if (dueTime <= this.clock) { dueTime = this.clock + 1; } return _super.prototype.scheduleAbsoluteWithState.call(this, state, dueTime, action); }; /** * Adds a relative virtual time to an absolute virtual time value. * * @param absolute Absolute virtual time value. * @param relative Relative virtual time value to add. * @return Resulting absolute virtual time sum value. */ TestScheduler.prototype.add = function (absolute, relative) { return absolute + relative; }; /** * Converts the absolute virtual time value to a DateTimeOffset value. * * @param absolute Absolute virtual time value to convert. * @return Corresponding DateTimeOffset value. */ TestScheduler.prototype.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @param timeSpan TimeSpan value to convert. * @return Corresponding relative virtual time value. */ TestScheduler.prototype.toRelative = function (timeSpan) { return timeSpan; }; /** * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. * * @param create Factory method to create an observable sequence. * @param created Virtual time at which to invoke the factory to create an observable sequence. * @param subscribed Virtual time at which to subscribe to the created observable sequence. * @param disposed Virtual time at which to dispose the subscription. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithTiming = function (create, created, subscribed, disposed) { var observer = this.createObserver(), source, subscription; this.scheduleAbsoluteWithState(null, created, function () { source = create(); return disposableEmpty; }); this.scheduleAbsoluteWithState(null, subscribed, function () { subscription = source.subscribe(observer); return disposableEmpty; }); this.scheduleAbsoluteWithState(null, disposed, function () { subscription.dispose(); return disposableEmpty; }); this.start(); return observer; }; /** * Starts the test scheduler and uses the specified virtual time to dispose the subscription to the sequence obtained through the factory function. * Default virtual times are used for factory invocation and sequence subscription. * * @param create Factory method to create an observable sequence. * @param disposed Virtual time at which to dispose the subscription. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithDispose = function (create, disposed) { return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, disposed); }; /** * Starts the test scheduler and uses default virtual times to invoke the factory function, to subscribe to the resulting sequence, and to dispose the subscription. * * @param create Factory method to create an observable sequence. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithCreate = function (create) { return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, ReactiveTest.disposed); }; /** * Creates a hot observable using the specified timestamped notification messages either as an array or arguments. * * @param messages Notifications to surface through the created sequence at their specified absolute virtual times. * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createHotObservable = function () { var messages = argsOrArray(arguments, 0); return new HotObservable(this, messages); }; /** * Creates a cold observable using the specified timestamped notification messages either as an array or arguments. * * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createColdObservable = function () { var messages = argsOrArray(arguments, 0); return new ColdObservable(this, messages); }; /** * Creates an observer that records received notification messages and timestamps those. * * @return Observer that can be used to assert the timing of received notifications. */ TestScheduler.prototype.createObserver = function () { return new MockObserver(this); }; return TestScheduler; })(VirtualTimeScheduler); return Rx; })); },{"./rx.all":25}],27:[function(require,module,exports){ var Rx = require('./dist/rx.all'); require('./dist/rx.testing'); // Add specific Node functions var EventEmitter = require('events').EventEmitter, Observable = Rx.Observable; Rx.Node = { /** * @deprecated Use Rx.Observable.fromCallback from rx.async.js instead. * * Converts a callback function to an observable sequence. * * @param {Function} func Function to convert to an asynchronous function. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Function} Asynchronous function. */ fromCallback: function (func, context, selector) { return Observable.fromCallback(func, context, selector); }, /** * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. * * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ fromNodeCallback: function (func, context, selector) { return Observable.fromNodeCallback(func, context, selector); }, /** * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. * * Handles an event from the given EventEmitter as an observable sequence. * * @param {EventEmitter} eventEmitter The EventEmitter to subscribe to the given event. * @param {String} eventName The event name to subscribe * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence generated from the named event from the given EventEmitter. The data will be returned as an array of arguments to the handler. */ fromEvent: function (eventEmitter, eventName, selector) { return Observable.fromEvent(eventEmitter, eventName, selector); }, /** * Converts the given observable sequence to an event emitter with the given event name. * The errors are handled on the 'error' event and completion on the 'end' event. * @param {Observable} observable The observable sequence to convert to an EventEmitter. * @param {String} eventName The event name to emit onNext calls. * @returns {EventEmitter} An EventEmitter which emits the given eventName for each onNext call in addition to 'error' and 'end' events. * You must call publish in order to invoke the subscription on the Observable sequuence. */ toEventEmitter: function (observable, eventName, selector) { var e = new EventEmitter(); // Used to publish the events from the observable e.publish = function () { e.subscription = observable.subscribe( function (x) { var result = x; if (selector) { try { result = selector(x); } catch (e) { e.emit('error', e); return; } } e.emit(eventName, result); }, function (err) { e.emit('error', err); }, function () { e.emit('end'); }); }; return e; }, /** * Converts a flowing stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @param {String} [finishEventName] Event that notifies about closed stream. ("end" by default) * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and finish events like `end` or `finish`. */ fromStream: function (stream, finishEventName) { return Observable.create(function (observer) { function dataHandler (data) { observer.onNext(data); } function errorHandler (err) { observer.onError(err); } function endHandler () { observer.onCompleted(); } if (!finishEventName) { finishEventName = 'end'; } stream.addListener('data', dataHandler); stream.addListener('error', errorHandler); stream.addListener(finishEventName, endHandler); return function () { stream.removeListener('data', dataHandler); stream.removeListener('error', errorHandler); stream.removeListener(finishEventName, endHandler); }; }).publish().refCount(); }, /** * Converts a flowing readable stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'end' events. */ fromReadableStream: function (stream) { return this.fromStream(stream, 'end'); }, /** * Converts a flowing writeable stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'finish' events. */ fromWritableStream: function (stream) { return this.fromStream(stream, 'finish'); }, /** * Converts a flowing transform stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'finish' events. */ fromTransformStream: function (stream) { return this.fromStream(stream, 'finish'); }, /** * Writes an observable sequence to a stream * @param {Observable} observable Observable sequence to write to a stream. * @param {Stream} stream The stream to write to. * @param {String} [encoding] The encoding of the item to write. * @returns {Disposable} The subscription handle. */ writeToStream: function (observable, stream, encoding) { return observable.subscribe( function (x) { stream.write(x, encoding); }, function (err) { stream.emit('error', err); }, function () { // Hack check because STDIO is not closable !stream._isStdio && stream.end(); }); } }; module.exports = Rx; },{"./dist/rx.all":25,"./dist/rx.testing":26,"events":2}],28:[function(require,module,exports){ var createElement = require("vdom/create-element") module.exports = createElement },{"vdom/create-element":32}],29:[function(require,module,exports){ var diff = require("vtree/diff") module.exports = diff },{"vtree/diff":38}],30:[function(require,module,exports){ module.exports = isObject function isObject(x) { return typeof x === "object" && x !== null } },{}],31:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("vtree/is-vhook") module.exports = applyProperties function applyProperties(node, props, previous) { for (var propName in props) { var propValue = props[propName] if (propValue === undefined) { removeProperty(node, props, previous, propName); } else if (isHook(propValue)) { propValue.hook(node, propName, previous ? previous[propName] : undefined) } else { if (isObject(propValue)) { patchObject(node, props, previous, propName, propValue); } else if (propValue !== undefined) { node[propName] = propValue } } } } function removeProperty(node, props, previous, propName) { if (previous) { var previousValue = previous[propName] if (!isHook(previousValue)) { if (propName === "attributes") { for (var attrName in previousValue) { node.removeAttribute(attrName) } } else if (propName === "style") { for (var i in previousValue) { node.style[i] = "" } } else if (typeof previousValue === "string") { node[propName] = "" } else { node[propName] = null } } } } function patchObject(node, props, previous, propName, propValue) { var previousValue = previous ? previous[propName] : undefined // Set attributes if (propName === "attributes") { for (var attrName in propValue) { var attrValue = propValue[attrName] if (attrValue === undefined) { node.removeAttribute(attrName) } else { node.setAttribute(attrName, attrValue) } } return } if(previousValue && isObject(previousValue) && getPrototype(previousValue) !== getPrototype(propValue)) { node[propName] = propValue return } if (!isObject(node[propName])) { node[propName] = {} } var replacer = propName === "style" ? "" : undefined for (var k in propValue) { var value = propValue[k] node[propName][k] = (value === undefined) ? replacer : value } } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"is-object":30,"vtree/is-vhook":41}],32:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") var isVNode = require("vtree/is-vnode") var isVText = require("vtree/is-vtext") var isWidget = require("vtree/is-widget") var handleThunk = require("vtree/handle-thunk") module.exports = createElement function createElement(vnode, opts) { var doc = opts ? opts.document || document : document var warn = opts ? opts.warn : null vnode = handleThunk(vnode).a if (isWidget(vnode)) { return vnode.init() } else if (isVText(vnode)) { return doc.createTextNode(vnode.text) } else if (!isVNode(vnode)) { if (warn) { warn("Item is not a valid virtual dom node", vnode) } return null } var node = (vnode.namespace === null) ? doc.createElement(vnode.tagName) : doc.createElementNS(vnode.namespace, vnode.tagName) var props = vnode.properties applyProperties(node, props) var children = vnode.children for (var i = 0; i < children.length; i++) { var childNode = createElement(children[i], opts) if (childNode) { node.appendChild(childNode) } } return node } },{"./apply-properties":31,"global/document":34,"vtree/handle-thunk":39,"vtree/is-vnode":42,"vtree/is-vtext":43,"vtree/is-widget":44}],33:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. // We only recurse into a DOM node if we know that it contains a child of // interest. var noChild = {} module.exports = domIndex function domIndex(rootNode, tree, indices, nodes) { if (!indices || indices.length === 0) { return {} } else { indices.sort(ascending) return recurse(rootNode, tree, indices, nodes, 0) } } function recurse(rootNode, tree, indices, nodes, rootIndex) { nodes = nodes || {} if (rootNode) { if (indexInRange(indices, rootIndex, rootIndex)) { nodes[rootIndex] = rootNode } var vChildren = tree.children if (vChildren) { var childNodes = rootNode.childNodes for (var i = 0; i < tree.children.length; i++) { rootIndex += 1 var vChild = vChildren[i] || noChild var nextIndex = rootIndex + (vChild.count || 0) // skip recursion down the tree if there are no nodes down here if (indexInRange(indices, rootIndex, nextIndex)) { recurse(childNodes[i], vChild, indices, nodes, rootIndex) } rootIndex = nextIndex } } } return nodes } // Binary search for an index in the interval [left, right] function indexInRange(indices, left, right) { if (indices.length === 0) { return false } var minIndex = 0 var maxIndex = indices.length - 1 var currentIndex var currentItem while (minIndex <= maxIndex) { currentIndex = ((maxIndex + minIndex) / 2) >> 0 currentItem = indices[currentIndex] if (minIndex === maxIndex) { return currentItem >= left && currentItem <= right } else if (currentItem < left) { minIndex = currentIndex + 1 } else if (currentItem > right) { maxIndex = currentIndex - 1 } else { return true } } return false; } function ascending(a, b) { return a > b ? 1 : -1 } },{}],34:[function(require,module,exports){ module.exports=require(14) },{"min-document":4}],35:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("vtree/is-widget") var VPatch = require("vtree/vpatch") var render = require("./create-element") var updateWidget = require("./update-widget") module.exports = applyPatch function applyPatch(vpatch, domNode, renderOptions) { var type = vpatch.type var vNode = vpatch.vNode var patch = vpatch.patch switch (type) { case VPatch.REMOVE: return removeNode(domNode, vNode) case VPatch.INSERT: return insertNode(domNode, patch, renderOptions) case VPatch.VTEXT: return stringPatch(domNode, vNode, patch, renderOptions) case VPatch.WIDGET: return widgetPatch(domNode, vNode, patch, renderOptions) case VPatch.VNODE: return vNodePatch(domNode, vNode, patch, renderOptions) case VPatch.ORDER: reorderChildren(domNode, patch) return domNode case VPatch.PROPS: applyProperties(domNode, patch, vNode.properties) return domNode case VPatch.THUNK: return replaceRoot(domNode, renderOptions.patch(domNode, patch, renderOptions)) default: return domNode } } function removeNode(domNode, vNode) { var parentNode = domNode.parentNode if (parentNode) { parentNode.removeChild(domNode) } destroyWidget(domNode, vNode); return null } function insertNode(parentNode, vNode, renderOptions) { var newNode = render(vNode, renderOptions) if (parentNode) { parentNode.appendChild(newNode) } return parentNode } function stringPatch(domNode, leftVNode, vText, renderOptions) { var newNode if (domNode.nodeType === 3) { domNode.replaceData(0, domNode.length, vText.text) newNode = domNode } else { var parentNode = domNode.parentNode newNode = render(vText, renderOptions) if (parentNode) { parentNode.replaceChild(newNode, domNode) } } destroyWidget(domNode, leftVNode) return newNode } function widgetPatch(domNode, leftVNode, widget, renderOptions) { if (updateWidget(leftVNode, widget)) { return widget.update(leftVNode, domNode) || domNode } var parentNode = domNode.parentNode var newWidget = render(widget, renderOptions) if (parentNode) { parentNode.replaceChild(newWidget, domNode) } destroyWidget(domNode, leftVNode) return newWidget } function vNodePatch(domNode, leftVNode, vNode, renderOptions) { var parentNode = domNode.parentNode var newNode = render(vNode, renderOptions) if (parentNode) { parentNode.replaceChild(newNode, domNode) } destroyWidget(domNode, leftVNode) return newNode } function destroyWidget(domNode, w) { if (typeof w.destroy === "function" && isWidget(w)) { w.destroy(domNode) } } function reorderChildren(domNode, bIndex) { var children = [] var childNodes = domNode.childNodes var len = childNodes.length var i var reverseIndex = bIndex.reverse for (i = 0; i < len; i++) { children.push(domNode.childNodes[i]) } var insertOffset = 0 var move var node var insertNode for (i = 0; i < len; i++) { move = bIndex[i] if (move !== undefined && move !== i) { // the element currently at this index will be moved later so increase the insert offset if (reverseIndex[i] > i) { insertOffset++ } node = children[move] insertNode = childNodes[i + insertOffset] if (node !== insertNode) { domNode.insertBefore(node, insertNode) } // the moved element came from the front of the array so reduce the insert offset if (move < i) { insertOffset-- } } // element at this index is scheduled to be removed so increase insert offset if (i in bIndex.removes) { insertOffset++ } } } function replaceRoot(oldRoot, newRoot) { if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) { console.log(oldRoot) oldRoot.parentNode.replaceChild(newRoot, oldRoot) } return newRoot; } },{"./apply-properties":31,"./create-element":32,"./update-widget":37,"vtree/is-widget":44,"vtree/vpatch":46}],36:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") var domIndex = require("./dom-index") var patchOp = require("./patch-op") module.exports = patch function patch(rootNode, patches) { return patchRecursive(rootNode, patches) } function patchRecursive(rootNode, patches, renderOptions) { var indices = patchIndices(patches) if (indices.length === 0) { return rootNode } var index = domIndex(rootNode, patches.a, indices) var ownerDocument = rootNode.ownerDocument if (!renderOptions) { renderOptions = { patch: patchRecursive } if (ownerDocument !== document) { renderOptions.document = ownerDocument } } for (var i = 0; i < indices.length; i++) { var nodeIndex = indices[i] rootNode = applyPatch(rootNode, index[nodeIndex], patches[nodeIndex], renderOptions) } return rootNode } function applyPatch(rootNode, domNode, patchList, renderOptions) { if (!domNode) { return rootNode } var newNode if (isArray(patchList)) { for (var i = 0; i < patchList.length; i++) { newNode = patchOp(patchList[i], domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } } else { newNode = patchOp(patchList, domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } return rootNode } function patchIndices(patches) { var indices = [] for (var key in patches) { if (key !== "a") { indices.push(Number(key)) } } return indices } },{"./dom-index":33,"./patch-op":35,"global/document":34,"x-is-array":47}],37:[function(require,module,exports){ var isWidget = require("vtree/is-widget") module.exports = updateWidget function updateWidget(a, b) { if (isWidget(a) && isWidget(b)) { if ("name" in a && "name" in b) { return a.id === b.id } else { return a.init === b.init } } return false } },{"vtree/is-widget":44}],38:[function(require,module,exports){ var isArray = require("x-is-array") var isObject = require("is-object") var VPatch = require("./vpatch") var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") var handleThunk = require("./handle-thunk") module.exports = diff function diff(a, b) { var patch = { a: a } walk(a, b, patch, 0) return patch } function walk(a, b, patch, index) { if (a === b) { if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else { hooks(b, patch, index) } return } var apply = patch[index] if (b == null) { apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b)) destroyWidgets(a, patch, index) } else if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else if (isVNode(b)) { if (isVNode(a)) { if (a.tagName === b.tagName && a.namespace === b.namespace && a.key === b.key) { var propsPatch = diffProps(a.properties, b.properties, b.hooks) if (propsPatch) { apply = appendPatch(apply, new VPatch(VPatch.PROPS, a, propsPatch)) } } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) destroyWidgets(a, patch, index) } apply = diffChildren(a, b, patch, apply, index) } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) destroyWidgets(a, patch, index) } } else if (isVText(b)) { if (!isVText(a)) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) destroyWidgets(a, patch, index) } else if (a.text !== b.text) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) } } else if (isWidget(b)) { apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) if (!isWidget(a)) { destroyWidgets(a, patch, index) } } if (apply) { patch[index] = apply } } function diffProps(a, b, hooks) { var diff for (var aKey in a) { if (!(aKey in b)) { diff = diff || {} diff[aKey] = undefined } var aValue = a[aKey] var bValue = b[aKey] if (hooks && aKey in hooks) { diff = diff || {} diff[aKey] = bValue } else { if (isObject(aValue) && isObject(bValue)) { if (getPrototype(bValue) !== getPrototype(aValue)) { diff = diff || {} diff[aKey] = bValue } else { var objectDiff = diffProps(aValue, bValue) if (objectDiff) { diff = diff || {} diff[aKey] = objectDiff } } } else if (aValue !== bValue) { diff = diff || {} diff[aKey] = bValue } } } for (var bKey in b) { if (!(bKey in a)) { diff = diff || {} diff[bKey] = b[bKey] } } return diff } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } function diffChildren(a, b, patch, apply, index) { var aChildren = a.children var bChildren = reorder(aChildren, b.children) var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen for (var i = 0; i < len; i++) { var leftNode = aChildren[i] var rightNode = bChildren[i] index += 1 if (!leftNode) { if (rightNode) { // Excess nodes in b need to be added apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode)) } } else if (!rightNode) { if (leftNode) { // Excess nodes in a need to be removed patch[index] = new VPatch(VPatch.REMOVE, leftNode, null) destroyWidgets(leftNode, patch, index) } } else { walk(leftNode, rightNode, patch, index) } if (isVNode(leftNode) && leftNode.count) { index += leftNode.count } } if (bChildren.moves) { // Reorder nodes last apply = appendPatch(apply, new VPatch(VPatch.ORDER, a, bChildren.moves)) } return apply } // Patch records for all destroyed widgets must be added because we need // a DOM node reference for the destroy function function destroyWidgets(vNode, patch, index) { if (isWidget(vNode)) { if (typeof vNode.destroy === "function") { patch[index] = new VPatch(VPatch.REMOVE, vNode, null) } } else if (isVNode(vNode) && vNode.hasWidgets) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 destroyWidgets(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } // Create a sub-patch for thunks function thunks(a, b, patch, index) { var nodes = handleThunk(a, b); var thunkPatch = diff(nodes.a, nodes.b) if (hasPatches(thunkPatch)) { patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) } } function hasPatches(patch) { for (var index in patch) { if (index !== "a") { return true; } } return false; } // Execute hooks when two nodes are identical function hooks(vNode, patch, index) { if (isVNode(vNode)) { if (vNode.hooks) { patch[index] = new VPatch(VPatch.PROPS, vNode.hooks, vNode.hooks) } if (vNode.descendantHooks) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 hooks(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } } // List diff, naive left to right reordering function reorder(aChildren, bChildren) { var bKeys = keyIndex(bChildren) if (!bKeys) { return bChildren } var aKeys = keyIndex(aChildren) if (!aKeys) { return bChildren } var bMatch = {}, aMatch = {} for (var key in bKeys) { bMatch[bKeys[key]] = aKeys[key] } for (var key in aKeys) { aMatch[aKeys[key]] = bKeys[key] } var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen var shuffle = [] var freeIndex = 0 var i = 0 var moveIndex = 0 var moves = {} var removes = moves.removes = {} var reverse = moves.reverse = {} var hasMoves = false while (freeIndex < len) { var move = aMatch[i] if (move !== undefined) { shuffle[i] = bChildren[move] if (move !== moveIndex) { moves[move] = moveIndex reverse[moveIndex] = move hasMoves = true } moveIndex++ } else if (i in aMatch) { shuffle[i] = undefined removes[i] = moveIndex++ hasMoves = true } else { while (bMatch[freeIndex] !== undefined) { freeIndex++ } if (freeIndex < len) { var freeChild = bChildren[freeIndex] if (freeChild) { shuffle[i] = freeChild if (freeIndex !== moveIndex) { hasMoves = true moves[freeIndex] = moveIndex reverse[moveIndex] = freeIndex } moveIndex++ } freeIndex++ } } i++ } if (hasMoves) { shuffle.moves = moves } return shuffle } function keyIndex(children) { var i, keys for (i = 0; i < children.length; i++) { var child = children[i] if (child.key !== undefined) { keys = keys || {} keys[child.key] = i } } return keys } function appendPatch(apply, patch) { if (apply) { if (isArray(apply)) { apply.push(patch) } else { apply = [apply, patch] } return apply } else { return patch } } },{"./handle-thunk":39,"./is-thunk":40,"./is-vnode":42,"./is-vtext":43,"./is-widget":44,"./vpatch":46,"is-object":30,"x-is-array":47}],39:[function(require,module,exports){ var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") module.exports = handleThunk function handleThunk(a, b) { var renderedA = a var renderedB = b if (isThunk(b)) { renderedB = renderThunk(b, a) } if (isThunk(a)) { renderedA = renderThunk(a, null) } return { a: renderedA, b: renderedB } } function renderThunk(thunk, previous) { var renderedThunk = thunk.vnode if (!renderedThunk) { renderedThunk = thunk.vnode = thunk.render(previous) } if (!(isVNode(renderedThunk) || isVText(renderedThunk) || isWidget(renderedThunk))) { throw new Error("thunk did not return a valid node"); } return renderedThunk } },{"./is-thunk":40,"./is-vnode":42,"./is-vtext":43,"./is-widget":44}],40:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } },{}],41:[function(require,module,exports){ module.exports = isHook function isHook(hook) { return hook && typeof hook.hook === "function" && !hook.hasOwnProperty("hook") } },{}],42:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } },{"./version":45}],43:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } },{"./version":45}],44:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } },{}],45:[function(require,module,exports){ module.exports = "1" },{}],46:[function(require,module,exports){ var version = require("./version") VirtualPatch.NONE = 0 VirtualPatch.VTEXT = 1 VirtualPatch.VNODE = 2 VirtualPatch.WIDGET = 3 VirtualPatch.PROPS = 4 VirtualPatch.ORDER = 5 VirtualPatch.INSERT = 6 VirtualPatch.REMOVE = 7 VirtualPatch.THUNK = 8 module.exports = VirtualPatch function VirtualPatch(type, vNode, patch) { this.type = Number(type) this.vNode = vNode this.patch = patch } VirtualPatch.prototype.version = version VirtualPatch.prototype.type = "VirtualPatch" },{"./version":45}],47:[function(require,module,exports){ var nativeIsArray = Array.isArray var toString = Object.prototype.toString module.exports = nativeIsArray || isArray function isArray(obj) { return toString.call(obj) === "[object Array]" } },{}],48:[function(require,module,exports){ var patch = require("vdom/patch") module.exports = patch },{"vdom/patch":36}],49:[function(require,module,exports){ var DataSet = require("data-set") module.exports = DataSetHook; function DataSetHook(value) { if (!(this instanceof DataSetHook)) { return new DataSetHook(value); } this.value = value; } DataSetHook.prototype.hook = function (node, propertyName) { var ds = DataSet(node) var propName = propertyName.substr(5) ds[propName] = this.value; }; },{"data-set":54}],50:[function(require,module,exports){ var DataSet = require("data-set") module.exports = DataSetHook; function DataSetHook(value) { if (!(this instanceof DataSetHook)) { return new DataSetHook(value); } this.value = value; } DataSetHook.prototype.hook = function (node, propertyName) { var ds = DataSet(node) var propName = propertyName.substr(3) ds[propName] = this.value; }; },{"data-set":54}],51:[function(require,module,exports){ module.exports = SoftSetHook; function SoftSetHook(value) { if (!(this instanceof SoftSetHook)) { return new SoftSetHook(value); } this.value = value; } SoftSetHook.prototype.hook = function (node, propertyName) { if (node[propertyName] !== this.value) { node[propertyName] = this.value; } }; },{}],52:[function(require,module,exports){ var VNode = require("vtree/vnode.js") var VText = require("vtree/vtext.js") var isVNode = require("vtree/is-vnode") var isVText = require("vtree/is-vtext") var isWidget = require("vtree/is-widget") var isHook = require("vtree/is-vhook") var isVThunk = require("vtree/is-thunk") var TypedError = require("error/typed") var parseTag = require("./parse-tag.js") var softSetHook = require("./hooks/soft-set-hook.js") var dataSetHook = require("./hooks/data-set-hook.js") var evHook = require("./hooks/ev-hook.js") var UnexpectedVirtualElement = TypedError({ type: "virtual-hyperscript.unexpected.virtual-element", message: "Unexpected virtual child passed to h().\n" + "Expected a VNode / Vthunk / VWidget / string but:\n" + "got a {foreignObjectStr}.\n" + "The parent vnode is {parentVnodeStr}.\n" + "Suggested fix: change your `h(..., [ ... ])` callsite.", foreignObjectStr: null, parentVnodeStr: null, foreignObject: null, parentVnode: null }) module.exports = h function h(tagName, properties, children) { var childNodes = [] var tag, props, key, namespace if (!children && isChildren(properties)) { children = properties props = {} } props = props || properties || {} tag = parseTag(tagName, props) // support keys if ("key" in props) { key = props.key props.key = undefined } // support namespace if ("namespace" in props) { namespace = props.namespace props.namespace = undefined } // fix cursor bug if (tag === "input" && "value" in props && props.value !== undefined && !isHook(props.value) ) { props.value = softSetHook(props.value) } var keys = Object.keys(props) var propName, value for (var j = 0; j < keys.length; j++) { propName = keys[j] value = props[propName] if (isHook(value)) { continue } // add data-foo support if (propName.substr(0, 5) === "data-") { props[propName] = dataSetHook(value) } // add ev-foo support if (propName.substr(0, 3) === "ev-") { props[propName] = evHook(value) } } if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props) } var node = new VNode(tag, props, childNodes, key, namespace) return node } function addChild(c, childNodes, tag, props) { if (typeof c === "string") { childNodes.push(new VText(c)) } else if (isChild(c)) { childNodes.push(c) } else if (Array.isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props) } } else if (c === null || c === undefined) { return } else { throw UnexpectedVirtualElement({ foreignObjectStr: JSON.stringify(c), foreignObject: c, parentVnodeStr: JSON.stringify({ tagName: tag, properties: props }), parentVnode: { tagName: tag, properties: props } }) } } function isChild(x) { return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x) } function isChildren(x) { return typeof x === "string" || Array.isArray(x) || isChild(x) } },{"./hooks/data-set-hook.js":49,"./hooks/ev-hook.js":50,"./hooks/soft-set-hook.js":51,"./parse-tag.js":70,"error/typed":61,"vtree/is-thunk":62,"vtree/is-vhook":63,"vtree/is-vnode":64,"vtree/is-vtext":65,"vtree/is-widget":66,"vtree/vnode.js":68,"vtree/vtext.js":69}],53:[function(require,module,exports){ module.exports=require(10) },{}],54:[function(require,module,exports){ arguments[4][11][0].apply(exports,arguments) },{"./create-hash.js":53,"individual":55,"weakmap-shim/create-store":56}],55:[function(require,module,exports){ module.exports=require(15) },{}],56:[function(require,module,exports){ module.exports=require(12) },{"./hidden-store.js":57}],57:[function(require,module,exports){ module.exports=require(13) },{}],58:[function(require,module,exports){ module.exports = function(obj) { if (typeof obj === 'string') return camelCase(obj); return walk(obj); }; function walk (obj) { if (!obj || typeof obj !== 'object') return obj; if (isDate(obj) || isRegex(obj)) return obj; if (isArray(obj)) return map(obj, walk); return reduce(objectKeys(obj), function (acc, key) { var camel = camelCase(key); acc[camel] = walk(obj[key]); return acc; }, {}); } function camelCase(str) { return str.replace(/[_.-](\w|$)/g, function (_,x) { return x.toUpperCase(); }); } var isArray = Array.isArray || function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; var isDate = function (obj) { return Object.prototype.toString.call(obj) === '[object Date]'; }; var isRegex = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var has = Object.prototype.hasOwnProperty; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } function reduce (xs, f, acc) { if (xs.reduce) return xs.reduce(f, acc); for (var i = 0; i < xs.length; i++) { acc = f(acc, xs[i], i); } return acc; } },{}],59:[function(require,module,exports){ var nargs = /\{([0-9a-zA-Z]+)\}/g var slice = Array.prototype.slice module.exports = template function template(string) { var args if (arguments.length === 2 && typeof arguments[1] === "object") { args = arguments[1] } else { args = slice.call(arguments, 1) } if (!args || !args.hasOwnProperty) { args = {} } return string.replace(nargs, function replaceArg(match, i, index) { var result if (string[index - 1] === "{" && string[index + match.length] === "}") { return i } else { result = args.hasOwnProperty(i) ? args[i] : null if (result === null || result === undefined) { return "" } return result } }) } },{}],60:[function(require,module,exports){ module.exports = extend function extend(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } },{}],61:[function(require,module,exports){ var camelize = require("camelize") var template = require("string-template") var extend = require("xtend/mutable") module.exports = TypedError function TypedError(args) { if (!args) { throw new Error("args is required"); } if (!args.type) { throw new Error("args.type is required"); } if (!args.message) { throw new Error("args.message is required"); } var message = args.message if (args.type && !args.name) { var errorName = camelize(args.type) + "Error" args.name = errorName[0].toUpperCase() + errorName.substr(1) } createError.type = args.type; createError._name = args.name; return createError; function createError(opts) { var result = new Error() Object.defineProperty(result, "type", { value: result.type, enumerable: true, writable: true, configurable: true }) var options = extend({}, args, opts) extend(result, options) result.message = template(message, options) return result } } },{"camelize":58,"string-template":59,"xtend/mutable":60}],62:[function(require,module,exports){ module.exports=require(40) },{}],63:[function(require,module,exports){ module.exports=require(41) },{}],64:[function(require,module,exports){ module.exports=require(42) },{"./version":67}],65:[function(require,module,exports){ module.exports=require(43) },{"./version":67}],66:[function(require,module,exports){ module.exports=require(44) },{}],67:[function(require,module,exports){ module.exports=require(45) },{}],68:[function(require,module,exports){ var version = require("./version") var isVNode = require("./is-vnode") var isWidget = require("./is-widget") var isVHook = require("./is-vhook") module.exports = VirtualNode var noProperties = {} var noChildren = [] function VirtualNode(tagName, properties, children, key, namespace) { this.tagName = tagName this.properties = properties || noProperties this.children = children || noChildren this.key = key != null ? String(key) : undefined this.namespace = (typeof namespace === "string") ? namespace : null var count = (children && children.length) || 0 var descendants = 0 var hasWidgets = false var descendantHooks = false var hooks for (var propName in properties) { if (properties.hasOwnProperty(propName)) { var property = properties[propName] if (isVHook(property)) { if (!hooks) { hooks = {} } hooks[propName] = property } } } for (var i = 0; i < count; i++) { var child = children[i] if (isVNode(child)) { descendants += child.count || 0 if (!hasWidgets && child.hasWidgets) { hasWidgets = true } if (!descendantHooks && (child.hooks || child.descendantHooks)) { descendantHooks = true } } else if (!hasWidgets && isWidget(child)) { if (typeof child.destroy === "function") { hasWidgets = true } } } this.count = count + descendants this.hasWidgets = hasWidgets this.hooks = hooks this.descendantHooks = descendantHooks } VirtualNode.prototype.version = version VirtualNode.prototype.type = "VirtualNode" },{"./is-vhook":63,"./is-vnode":64,"./is-widget":66,"./version":67}],69:[function(require,module,exports){ var version = require("./version") module.exports = VirtualText function VirtualText(text) { this.text = String(text) } VirtualText.prototype.version = version VirtualText.prototype.type = "VirtualText" },{"./version":67}],70:[function(require,module,exports){ var classIdSplit = /([\.#]?[a-zA-Z0-9_:-]+)/ var notClassId = /^\.|#/ module.exports = parseTag function parseTag(tag, props) { if (!tag) { return "div" } var noId = !("id" in props) var tagParts = tag.split(classIdSplit) var tagName = null if (notClassId.test(tagParts[1])) { tagName = "div" } var classes, part, type, i for (i = 0; i < tagParts.length; i++) { part = tagParts[i] if (!part) { continue } type = part.charAt(0) if (!tagName) { tagName = part } else if (type === ".") { classes = classes || [] classes.push(part.substring(1, part.length)) } else if (type === "#" && noId) { props.id = part.substring(1, part.length) } } if (classes) { if (props.className) { classes.push(props.className) } props.className = classes.join(" ") } return tagName ? tagName.toLowerCase() : "div" } },{}],71:[function(require,module,exports){ 'use strict'; var binder = require('mvi-example/utils/binder'); var renderer = require('mvi-example/renderer'); var ItemsModel = require('mvi-example/models/items'); var ItemsView = require('mvi-example/views/items'); var ItemsIntent = require('mvi-example/intents/items'); window.onload = function () { binder(ItemsModel, ItemsView, ItemsIntent); renderer.init(); }; },{"mvi-example/intents/items":19,"mvi-example/models/items":20,"mvi-example/renderer":21,"mvi-example/utils/binder":22,"mvi-example/views/items":24}]},{},[71]) ;
dist/js/app.js
;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // // The shims in this file are not fully implemented shims for the ES5 // features, but do work for the particular usecases there is in // the other modules. // var toString = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; // Array.isArray is supported in IE9 function isArray(xs) { return toString.call(xs) === '[object Array]'; } exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; // Array.prototype.indexOf is supported in IE9 exports.indexOf = function indexOf(xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (x === xs[i]) return i; } return -1; }; // Array.prototype.filter is supported in IE9 exports.filter = function filter(xs, fn) { if (xs.filter) return xs.filter(fn); var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; }; // Array.prototype.forEach is supported in IE9 exports.forEach = function forEach(xs, fn, self) { if (xs.forEach) return xs.forEach(fn, self); for (var i = 0; i < xs.length; i++) { fn.call(self, xs[i], i, xs); } }; // Array.prototype.map is supported in IE9 exports.map = function map(xs, fn) { if (xs.map) return xs.map(fn); var out = new Array(xs.length); for (var i = 0; i < xs.length; i++) { out[i] = fn(xs[i], i, xs); } return out; }; // Array.prototype.reduce is supported in IE9 exports.reduce = function reduce(array, callback, opt_initialValue) { if (array.reduce) return array.reduce(callback, opt_initialValue); var value, isValueSet = false; if (2 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (var i = 0, l = array.length; l > i; ++i) { if (array.hasOwnProperty(i)) { if (isValueSet) { value = callback(value, array[i], i, array); } else { value = array[i]; isValueSet = true; } } } return value; }; // String.prototype.substr - negative index don't work in IE8 if ('ab'.substr(-1) !== 'b') { exports.substr = function (str, start, length) { // did we get a negative start, calculate how much it is from the beginning of the string if (start < 0) start = str.length + start; // call the original function return str.substr(start, length); }; } else { exports.substr = function (str, start, length) { return str.substr(start, length); }; } // String.prototype.trim is supported in IE9 exports.trim = function (str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); }; // Function.prototype.bind is supported in IE9 exports.bind = function () { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); if (fn.bind) return fn.bind.apply(fn, args); var self = args.shift(); return function () { fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); }; }; // Object.create is supported in IE9 function create(prototype, properties) { var object; if (prototype === null) { object = { '__proto__' : null }; } else { if (typeof prototype !== 'object') { throw new TypeError( 'typeof prototype[' + (typeof prototype) + '] != \'object\'' ); } var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (typeof properties !== 'undefined' && Object.defineProperties) { Object.defineProperties(object, properties); } return object; } exports.create = typeof Object.create === 'function' ? Object.create : create; // Object.keys and Object.getOwnPropertyNames is supported in IE9 however // they do show a description and number property on Error objects function notObject(object) { return ((typeof object != "object" && typeof object != "function") || object === null); } function keysShim(object) { if (notObject(object)) { throw new TypeError("Object.keys called on a non-object"); } var result = []; for (var name in object) { if (hasOwnProperty.call(object, name)) { result.push(name); } } return result; } // getOwnPropertyNames is almost the same as Object.keys one key feature // is that it returns hidden properties, since that can't be implemented, // this feature gets reduced so it just shows the length property on arrays function propertyShim(object) { if (notObject(object)) { throw new TypeError("Object.getOwnPropertyNames called on a non-object"); } var result = keysShim(object); if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { result.push('length'); } return result; } var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? Object.getOwnPropertyNames : propertyShim; if (new Error().hasOwnProperty('description')) { var ERROR_PROPERTY_FILTER = function (obj, array) { if (toString.call(obj) === '[object Error]') { array = exports.filter(array, function (name) { return name !== 'description' && name !== 'number' && name !== 'message'; }); } return array; }; exports.keys = function (object) { return ERROR_PROPERTY_FILTER(object, keys(object)); }; exports.getOwnPropertyNames = function (object) { return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); }; } else { exports.keys = keys; exports.getOwnPropertyNames = getOwnPropertyNames; } // Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements function valueObject(value, key) { return { value: value[key] }; } if (typeof Object.getOwnPropertyDescriptor === 'function') { try { Object.getOwnPropertyDescriptor({'a': 1}, 'a'); exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; } catch (e) { // IE8 dom element issue - use a try catch and default to valueObject exports.getOwnPropertyDescriptor = function (value, key) { try { return Object.getOwnPropertyDescriptor(value, key); } catch (e) { return valueObject(value, key); } }; } } else { exports.getOwnPropertyDescriptor = valueObject; } },{}],2:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!util.isNumber(n) || n < 0) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (util.isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (util.isUndefined(handler)) return false; if (util.isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (util.isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, util.isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (util.isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (util.isObject(this._events[type]) && !this._events[type].warned) { var m; if (!util.isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!util.isFunction(listener)) throw TypeError('listener must be a function'); function g() { this.removeListener(type, g); listener.apply(this, arguments); } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (util.isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (util.isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (util.isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (util.isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (util.isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; },{"util":3}],3:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var shims = require('_shims'); var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; shims.forEach(array, function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = shims.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = shims.getOwnPropertyNames(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } shims.forEach(keys, function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (shims.indexOf(ctx.seen, desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = shims.reduce(output, function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return shims.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && objectToString(e) === '[object Error]'; } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.binarySlice === 'function' ; } exports.isBuffer = isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = shims.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = shims.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } },{"_shims":1}],4:[function(require,module,exports){ },{}],5:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],6:[function(require,module,exports){ var DataSet = require("data-set") module.exports = addEvent function addEvent(target, type, handler) { var ds = DataSet(target) var events = ds[type] if (!events) { ds[type] = handler } else if (Array.isArray(events)) { if (events.indexOf(handler) === -1) { events.push(handler) } } else if (events !== handler) { ds[type] = [events, handler] } } },{"data-set":11}],7:[function(require,module,exports){ var globalDocument = require("global/document") var DataSet = require("data-set") var addEvent = require("./add-event.js") var removeEvent = require("./remove-event.js") var ProxyEvent = require("./proxy-event.js") module.exports = DOMDelegator function DOMDelegator(document) { document = document || globalDocument this.target = document.documentElement this.events = {} this.rawEventListeners = {} this.globalListeners = {} } DOMDelegator.prototype.addEventListener = addEvent DOMDelegator.prototype.removeEventListener = removeEvent DOMDelegator.prototype.addGlobalEventListener = function addGlobalEventListener(eventName, fn) { var listeners = this.globalListeners[eventName] if (!listeners) { listeners = this.globalListeners[eventName] = [] } if (listeners.indexOf(fn) === -1) { listeners.push(fn) } } DOMDelegator.prototype.removeGlobalEventListener = function removeGlobalEventListener(eventName, fn) { var listeners = this.globalListeners[eventName] if (!listeners) { return } var index = listeners.indexOf(fn) if (index !== -1) { listeners.splice(index, 1) } } DOMDelegator.prototype.listenTo = function listenTo(eventName) { if (this.events[eventName]) { return } this.events[eventName] = true listen(this, eventName) } DOMDelegator.prototype.unlistenTo = function unlistenTo(eventName) { if (!this.events[eventName]) { return } this.events[eventName] = false unlisten(this, eventName) } function listen(delegator, eventName) { var listener = delegator.rawEventListeners[eventName] if (!listener) { listener = delegator.rawEventListeners[eventName] = createHandler(eventName, delegator.globalListeners) } delegator.target.addEventListener(eventName, listener, true) } function unlisten(delegator, eventName) { var listener = delegator.rawEventListeners[eventName] if (!listener) { throw new Error("dom-delegator#unlistenTo: cannot " + "unlisten to " + eventName) } delegator.target.removeEventListener(eventName, listener, true) } function createHandler(eventName, globalListeners) { return handler function handler(ev) { var globalHandlers = globalListeners[eventName] || [] var listener = getListener(ev.target, eventName) var handlers = globalHandlers .concat(listener ? listener.handlers : []) if (handlers.length === 0) { return } var arg = new ProxyEvent(ev, listener) handlers.forEach(function (handler) { typeof handler === "function" ? handler(arg) : handler.handleEvent(arg) }) } } function getListener(target, type) { // terminate recursion if parent is `null` if (target === null) { return null } var ds = DataSet(target) // fetch list of handler fns for this event var handler = ds[type] var allHandler = ds.event if (!handler && !allHandler) { return getListener(target.parentNode, type) } var handlers = [].concat(handler || [], allHandler || []) return new Listener(target, handlers) } function Listener(target, handlers) { this.currentTarget = target this.handlers = handlers } },{"./add-event.js":6,"./proxy-event.js":17,"./remove-event.js":18,"data-set":11,"global/document":14}],8:[function(require,module,exports){ var Individual = require("individual") var cuid = require("cuid") var globalDocument = require("global/document") var DOMDelegator = require("./dom-delegator.js") var delegatorCache = Individual("__DOM_DELEGATOR_CACHE@9", { delegators: {} }) var commonEvents = [ "blur", "change", "click", "contextmenu", "dblclick", "error","focus", "focusin", "focusout", "input", "keydown", "keypress", "keyup", "load", "mousedown", "mouseup", "resize", "scroll", "select", "submit", "touchcancel", "touchend", "touchstart", "unload" ] /* Delegator is a thin wrapper around a singleton `DOMDelegator` instance. Only one DOMDelegator should exist because we do not want duplicate event listeners bound to the DOM. `Delegator` will also `listenTo()` all events unless every caller opts out of it */ module.exports = Delegator function Delegator(opts) { opts = opts || {} var document = opts.document || globalDocument var cacheKey = document["__DOM_DELEGATOR_CACHE_TOKEN@9"] if (!cacheKey) { cacheKey = document["__DOM_DELEGATOR_CACHE_TOKEN@9"] = cuid() } var delegator = delegatorCache.delegators[cacheKey] if (!delegator) { delegator = delegatorCache.delegators[cacheKey] = new DOMDelegator(document) } if (opts.defaultEvents !== false) { for (var i = 0; i < commonEvents.length; i++) { delegator.listenTo(commonEvents[i]) } } return delegator } },{"./dom-delegator.js":7,"cuid":9,"global/document":14,"individual":15}],9:[function(require,module,exports){ /** * cuid.js * Collision-resistant UID generator for browsers and node. * Sequential for fast db lookups and recency sorting. * Safe for element IDs and server-side lookups. * * Extracted from CLCTR * * Copyright (c) Eric Elliott 2012 * MIT License */ /*global window, navigator, document, require, process, module */ (function (app) { 'use strict'; var namespace = 'cuid', c = 0, blockSize = 4, base = 36, discreteValues = Math.pow(base, blockSize), pad = function pad(num, size) { var s = "000000000" + num; return s.substr(s.length-size); }, randomBlock = function randomBlock() { return pad((Math.random() * discreteValues << 0) .toString(base), blockSize); }, safeCounter = function () { c = (c < discreteValues) ? c : 0; c++; // this is not subliminal return c - 1; }, api = function cuid() { // Starting with a lowercase letter makes // it HTML element ID friendly. var letter = 'c', // hard-coded allows for sequential access // timestamp // warning: this exposes the exact date and time // that the uid was created. timestamp = (new Date().getTime()).toString(base), // Prevent same-machine collisions. counter, // A few chars to generate distinct ids for different // clients (so different computers are far less // likely to generate the same id) fingerprint = api.fingerprint(), // Grab some more chars from Math.random() random = randomBlock() + randomBlock(); counter = pad(safeCounter().toString(base), blockSize); return (letter + timestamp + counter + fingerprint + random); }; api.slug = function slug() { var date = new Date().getTime().toString(36), counter, print = api.fingerprint().slice(0,1) + api.fingerprint().slice(-1), random = randomBlock().slice(-2); counter = safeCounter().toString(36).slice(-4); return date.slice(-2) + counter + print + random; }; api.globalCount = function globalCount() { // We want to cache the results of this var cache = (function calc() { var i, count = 0; for (i in window) { count++; } return count; }()); api.globalCount = function () { return cache; }; return cache; }; api.fingerprint = function browserPrint() { return pad((navigator.mimeTypes.length + navigator.userAgent.length).toString(36) + api.globalCount().toString(36), 4); }; // don't change anything from here down. if (app.register) { app.register(namespace, api); } else if (typeof module !== 'undefined') { module.exports = api; } else { app[namespace] = api; } }(this.applitude || this)); },{}],10:[function(require,module,exports){ module.exports = createHash function createHash(elem) { var attributes = elem.attributes var hash = {} if (attributes === null || attributes === undefined) { return hash } for (var i = 0; i < attributes.length; i++) { var attr = attributes[i] if (attr.name.substr(0,5) !== "data-") { continue } hash[attr.name.substr(5)] = attr.value } return hash } },{}],11:[function(require,module,exports){ var createStore = require("weakmap-shim/create-store") var Individual = require("individual") var createHash = require("./create-hash.js") var hashStore = Individual("__DATA_SET_WEAKMAP@3", createStore()) module.exports = DataSet function DataSet(elem) { var store = hashStore(elem) if (!store.hash) { store.hash = createHash(elem) } return store.hash } },{"./create-hash.js":10,"individual":15,"weakmap-shim/create-store":12}],12:[function(require,module,exports){ var hiddenStore = require('./hidden-store.js'); module.exports = createStore; function createStore() { var key = {}; return function (obj) { if (typeof obj !== 'object' || obj === null) { throw new Error('Weakmap-shim: Key must be object') } var store = obj.valueOf(key); return store && store.identity === key ? store : hiddenStore(obj, key); }; } },{"./hidden-store.js":13}],13:[function(require,module,exports){ module.exports = hiddenStore; function hiddenStore(obj, key) { var store = { identity: key }; var valueOf = obj.valueOf; Object.defineProperty(obj, "valueOf", { value: function (value) { return value !== key ? valueOf.apply(this, arguments) : store; }, writable: true }); return store; } },{}],14:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = require('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } },{"min-document":4}],15:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};var root = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; module.exports = Individual function Individual(key, value) { if (root[key]) { return root[key] } Object.defineProperty(root, key, { value: value , configurable: true }) return value } },{}],16:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],17:[function(require,module,exports){ var inherits = require("inherits") var ALL_PROPS = [ "altKey", "bubbles", "cancelable", "ctrlKey", "eventPhase", "metaKey", "relatedTarget", "shiftKey", "target", "timeStamp", "type", "view", "which" ] var KEY_PROPS = ["char", "charCode", "key", "keyCode"] var MOUSE_PROPS = [ "button", "buttons", "clientX", "clientY", "layerX", "layerY", "offsetX", "offsetY", "pageX", "pageY", "screenX", "screenY", "toElement" ] var rkeyEvent = /^key|input/ var rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/ module.exports = ProxyEvent function ProxyEvent(ev, listener) { if (!(this instanceof ProxyEvent)) { return new ProxyEvent(ev, listener) } if (rkeyEvent.test(ev.type)) { return new KeyEvent(ev, listener) } else if (rmouseEvent.test(ev.type)) { return new MouseEvent(ev, listener) } for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } ProxyEvent.prototype.preventDefault = function () { this._rawEvent.preventDefault() } function MouseEvent(ev, listener) { for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } for (var j = 0; j < MOUSE_PROPS.length; j++) { var mousePropKey = MOUSE_PROPS[j] this[mousePropKey] = ev[mousePropKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } inherits(MouseEvent, ProxyEvent) function KeyEvent(ev, listener) { for (var i = 0; i < ALL_PROPS.length; i++) { var propKey = ALL_PROPS[i] this[propKey] = ev[propKey] } for (var j = 0; j < KEY_PROPS.length; j++) { var keyPropKey = KEY_PROPS[j] this[keyPropKey] = ev[keyPropKey] } this._rawEvent = ev this.currentTarget = listener ? listener.currentTarget : null } inherits(KeyEvent, ProxyEvent) },{"inherits":16}],18:[function(require,module,exports){ var DataSet = require("data-set") module.exports = removeEvent function removeEvent(target, type, handler) { var ds = DataSet(target) var events = ds[type] if (!events) { return } else if (Array.isArray(events)) { var index = events.indexOf(handler) if (index !== -1) { events.splice(index, 1) } } else if (events === handler) { ds[type] = null } } },{"data-set":11}],19:[function(require,module,exports){ 'use strict'; /* * ItemsIntent. Interprets raw user input and outputs model-friendly user * intents. */ var Rx = require('rx'); var replicate = require('mvi-example/utils/replicate'); var inputAddOneClicks$ = new Rx.Subject(); var inputAddManyClicks$ = new Rx.Subject(); var inputRemoveClicks$ = new Rx.Subject(); var inputItemColorChanged$ = new Rx.Subject(); var inputItemWidthChanged$ = new Rx.Subject(); function observe(ItemsView) { replicate(ItemsView.addOneClicks$, inputAddOneClicks$); replicate(ItemsView.addManyClicks$, inputAddManyClicks$); replicate(ItemsView.removeClicks$, inputRemoveClicks$); replicate(ItemsView.itemColorChanged$, inputItemColorChanged$); replicate(ItemsView.itemWidthChanged$, inputItemWidthChanged$); } var addItem$ = Rx.Observable .merge( inputAddOneClicks$.map(function () { return {operation: 'add', amount: 1}; }), inputAddManyClicks$.map(function () { return {operation: 'add', amount: 1000}; }) ); var removeItem$ = inputRemoveClicks$ .map(function (clickEvent) { return { operation: 'remove', id: Number(clickEvent.currentTarget.attributes['data-item-id'].value) }; }); var colorChanged$ = inputItemColorChanged$ .map(function (inputEvent) { return { operation: 'changeColor', id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), color: inputEvent.currentTarget.value } }); var widthChanged$ = inputItemWidthChanged$ .map(function (inputEvent) { return { operation: 'changeWidth', id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), width: Number(inputEvent.currentTarget.value) } }); module.exports = { observe: observe, addItem$: addItem$, removeItem$: removeItem$, colorChanged$: colorChanged$, widthChanged$: widthChanged$ }; },{"mvi-example/utils/replicate":23,"rx":27}],20:[function(require,module,exports){ 'use strict'; /* * ItemsModel. * As output, Observable of array of item data. * As input, ItemsIntent. */ var Rx = require('rx'); var replicate = require('mvi-example/utils/replicate'); var intentAddItem$ = new Rx.Subject(); var intentRemoveItem$ = new Rx.Subject(); var intentWidthChanged$ = new Rx.Subject(); var intentColorChanged$ = new Rx.Subject(); function observe(ItemsIntent) { replicate(ItemsIntent.addItem$, intentAddItem$); replicate(ItemsIntent.removeItem$, intentRemoveItem$); replicate(ItemsIntent.widthChanged$, intentWidthChanged$); replicate(ItemsIntent.colorChanged$, intentColorChanged$); } function createRandomItem() { var hexColor = Math.floor(Math.random() * 16777215).toString(16); while (hexColor.length < 6) { hexColor = '0' + hexColor; } hexColor = '#' + hexColor; var randomWidth = Math.floor(Math.random() * 800 + 200); return {color: hexColor, width: randomWidth}; } function reassignId(item, index) { return {id: index, color: item.color, width: item.width}; } var items$ = Rx.Observable.just([{id: 0, color: 'red', width: 300}]) .merge(intentAddItem$) .merge(intentRemoveItem$) .merge(intentColorChanged$) .merge(intentWidthChanged$) .scan(function (listItems, x) { if (Array.isArray(x)) { return x; } else if (x.operation === 'add') { var newItems = []; for (var i = 0; i < x.amount; i++) { newItems.push(createRandomItem()); } return listItems.concat(newItems).map(reassignId); } else if (x.operation === 'remove') { return listItems .filter(function (item) { return item.id !== x.id; }) .map(reassignId); } else if (x.operation === 'changeColor') { listItems[x.id].color = x.color; return listItems; } else if (x.operation === 'changeWidth') { listItems[x.id].width = x.width; return listItems; } else { return listItems; } }); module.exports = { observe: observe, items$: items$ }; },{"mvi-example/utils/replicate":23,"rx":27}],21:[function(require,module,exports){ 'use strict'; /* * Renderer component. * Subscribes to vtree observables of all view components * and renders them as real DOM elements to the browser. */ var h = require('virtual-hyperscript'); var VDOM = { createElement: require('virtual-dom/create-element'), diff: require('virtual-dom/diff'), patch: require('virtual-dom/patch') }; var DOMDelegator = require('dom-delegator'); var ItemsView = require('mvi-example/views/items'); var delegator; function renderVTreeStream(vtree$, containerSelector) { // Find and prepare the container var container = document.querySelector(containerSelector); if (container === null) { console.error('Couldn\'t render into unknown \'' + containerSelector + '\''); return false; } container.innerHTML = ''; // Make the DOM node bound to the VDOM node var rootNode = document.createElement('div'); container.appendChild(rootNode); vtree$.startWith(h()) .bufferWithCount(2, 1) .subscribe(function (buffer) { try { var oldVTree = buffer[0]; var newVTree = buffer[1]; rootNode = VDOM.patch(rootNode, VDOM.diff(oldVTree, newVTree)); } catch (err) { console.error(err); } }); return true; } function init() { delegator = new DOMDelegator(); renderVTreeStream(ItemsView.vtree$, '.js-container'); } module.exports = { init: init }; },{"dom-delegator":8,"mvi-example/views/items":24,"virtual-dom/create-element":28,"virtual-dom/diff":29,"virtual-dom/patch":48,"virtual-hyperscript":52}],22:[function(require,module,exports){ 'use strict'; /* * Important Model-View-Intent binding function. */ module.exports = function (model, view, intent) { if (view) { view.observe(model); } if (intent) { intent.observe(view); } if (model) { model.observe(intent); } }; },{}],23:[function(require,module,exports){ 'use strict'; /* * Utility functions */ /** * Forwards all notifications from the source observable to the given subject. * * @param {Rx.Observable} source the origin observable * @param {Rx.Subject} subject the destination subject * @return {Rx.Disposable} a disposable generated by a subscribe method */ function replicate(source, subject) { if (typeof source === 'undefined') { throw new Error('Cannot replicate() if source is undefined.'); } return source.subscribe( function replicationOnNext(x) { subject.onNext(x); }, function replicationOnError(err) { console.error(err); } ); } module.exports = replicate; },{}],24:[function(require,module,exports){ 'use strict'; /* * ItemsView. * As output, Observable of vtree (Virtual DOM tree). * As input, ItemsModel. */ var Rx = require('rx'); var h = require('virtual-hyperscript'); var replicate = require('mvi-example/utils/replicate'); var modelItems$ = new Rx.BehaviorSubject(null); var itemWidthChanged$ = new Rx.Subject(); var itemColorChanged$ = new Rx.Subject(); var removeClicks$ = new Rx.Subject(); var addOneClicks$ = new Rx.Subject(); var addManyClicks$ = new Rx.Subject(); function observe(ItemsModel) { replicate(ItemsModel.items$, modelItems$); } function vrenderTopButtons() { return h('div.topButtons', {}, [ h('button', {'ev-click': function (ev) { addOneClicks$.onNext(ev); }}, 'Add New Item' ), h('button', {'ev-click': function (ev) { addManyClicks$.onNext(ev); }}, 'Add Many Items' ) ]); } function vrenderItem(itemData) { return h('div', { style: { 'border': '1px solid #000', 'background': 'none repeat scroll 0% 0% ' + itemData.color, 'width': itemData.width + 'px', 'height': '70px', 'display': 'block', 'padding': '20px', 'margin': '10px 0px' }}, [ h('input', { type: 'text', value: itemData.color, 'attributes': {'data-item-id': itemData.id}, 'ev-input': function (ev) { itemColorChanged$.onNext(ev); } }), h('div', [ h('input', { type: 'range', min:'200', max:'1000', value: itemData.width, 'attributes': {'data-item-id': itemData.id}, 'ev-input': function (ev) { itemWidthChanged$.onNext(ev); } }) ]), h('div', String(itemData.width)), h('button', { 'attributes': {'data-item-id': itemData.id}, 'ev-click': function (ev) { removeClicks$.onNext(ev); } }, 'Remove') ] ); } var vtree$ = modelItems$ .map(function (itemsData) { return h('div.everything', {}, [ vrenderTopButtons(), itemsData.map(vrenderItem) ]); }); module.exports = { observe: observe, vtree$: vtree$, removeClicks$: removeClicks$, addOneClicks$: addOneClicks$, addManyClicks$: addManyClicks$, itemColorChanged$: itemColorChanged$, itemWidthChanged$: itemWidthChanged$ }; },{"mvi-example/utils/replicate":23,"rx":27,"virtual-hyperscript":52}],25:[function(require,module,exports){ var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >=0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value from the given index. */ observableProto.contains = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (observer) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { observer.onNext(false); observer.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { observer.onNext(true); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { observer.onNext(-1); observer.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { observer.onNext(i); observer.onCompleted(); } i++; }, observer.onError.bind(observer), function () { observer.onNext(-1); observer.onCompleted(); }); }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { count < len && (equal = comparer(value, second[count++])); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; if (!!root.Set) { /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { var source = this; return new AnonymousObservable(function (observer) { var s = new root.Set(); return source.subscribe( s.add.bind(s), observer.onError.bind(observer), function () { observer.onNext(s); observer.onCompleted(); }); }); }; } if (!!root.Map) { /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { observer.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { observer.onError(e); return; } } m.set(key, element); }, observer.onError.bind(observer), function () { observer.onNext(m); observer.onCompleted(); }); }); }; } var fnString = 'function'; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res){ if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThink(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn){ promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && obj.prototype.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj.throw === fnString; } function isObject(val) { return val && val.constructor === Object; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fan; if (isGenFun) { var args = slice.call(arguments), len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : error; gen = fn.apply(this, args); } else { done = done || error; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) res = slice.call(arguments, 1); if (err) { try { ret = gen.throw(err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function(){ if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; /** * Takes a function with a callback and turns it into a thunk. * @param {Function} A function with a callback such as fs.readFile * @returns {Function} A function, when executed will continue the state machine. */ Rx.denodify = function (fn) { return function (){ var args = slice.call(arguments), results, called, callback; args.push(function(){ results = arguments; if (callback && !called) { called = true; cb.apply(this, results); } }); fn.apply(this, args); return function (fn){ callback = fn; if (results && !called) { called = true; fn.apply(this, results); } } } }; /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch(exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( observer.onNext.bind(observer), function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); observer.onError(err); }, observer.onCompleted.bind(observer) ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && observer.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(observer); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this)); },{"__browserify_process":5}],26:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx.virtualtime', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx.all')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // Defaults var Observer = Rx.Observer, Observable = Rx.Observable, Notification = Rx.Notification, VirtualTimeScheduler = Rx.VirtualTimeScheduler, Disposable = Rx.Disposable, disposableEmpty = Disposable.empty, disposableCreate = Disposable.create, CompositeDisposable = Rx.CompositeDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, slice = Array.prototype.slice, inherits = Rx.internals.inherits, defaultComparer = Rx.internals.isEqual; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } function OnNextPredicate(predicate) { this.predicate = predicate; }; OnNextPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'N') { return false; } return this.predicate(other.value); }; function OnErrorPredicate(predicate) { this.predicate = predicate; }; OnErrorPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'E') { return false; } return this.predicate(other.exception); }; var ReactiveTest = Rx.ReactiveTest = { /** Default virtual time used for creation of observable sequences in unit tests. */ created: 100, /** Default virtual time used to subscribe to observable sequences in unit tests. */ subscribed: 200, /** Default virtual time used to dispose subscriptions in unit tests. */ disposed: 1000, /** * Factory method for an OnNext notification record at a given time with a given value or a predicate function. * * 1 - ReactiveTest.onNext(200, 42); * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; }); * * @param ticks Recorded virtual time the OnNext notification occurs. * @param value Recorded value stored in the OnNext notification or a predicate. * @return Recorded OnNext notification. */ onNext: function (ticks, value) { if (typeof value === 'function') { return new Recorded(ticks, new OnNextPredicate(value)); } return new Recorded(ticks, Notification.createOnNext(value)); }, /** * Factory method for an OnError notification record at a given time with a given error. * * 1 - ReactiveTest.onNext(200, new Error('error')); * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; }); * * @param ticks Recorded virtual time the OnError notification occurs. * @param exception Recorded exception stored in the OnError notification. * @return Recorded OnError notification. */ onError: function (ticks, exception) { if (typeof exception === 'function') { return new Recorded(ticks, new OnErrorPredicate(exception)); } return new Recorded(ticks, Notification.createOnError(exception)); }, /** * Factory method for an OnCompleted notification record at a given time. * * @param ticks Recorded virtual time the OnCompleted notification occurs. * @return Recorded OnCompleted notification. */ onCompleted: function (ticks) { return new Recorded(ticks, Notification.createOnCompleted()); }, /** * Factory method for a subscription record based on a given subscription and disposal time. * * @param start Virtual time indicating when the subscription was created. * @param end Virtual time indicating when the subscription was disposed. * @return Subscription object. */ subscribe: function (start, end) { return new Subscription(start, end); } }; /** * Creates a new object recording the production of the specified value at the given virtual time. * * @constructor * @param {Number} time Virtual time the value was produced on. * @param {Mixed} value Value that was produced. * @param {Function} comparer An optional comparer. */ var Recorded = Rx.Recorded = function (time, value, comparer) { this.time = time; this.value = value; this.comparer = comparer || defaultComparer; }; /** * Checks whether the given recorded object is equal to the current instance. * * @param {Recorded} other Recorded object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Recorded.prototype.equals = function (other) { return this.time === other.time && this.comparer(this.value, other.value); }; /** * Returns a string representation of the current Recorded value. * * @returns {String} String representation of the current Recorded value. */ Recorded.prototype.toString = function () { return this.value.toString() + '@' + this.time; }; /** * Creates a new subscription object with the given virtual subscription and unsubscription time. * * @constructor * @param {Number} subscribe Virtual time at which the subscription occurred. * @param {Number} unsubscribe Virtual time at which the unsubscription occurred. */ var Subscription = Rx.Subscription = function (start, end) { this.subscribe = start; this.unsubscribe = end || Number.MAX_VALUE; }; /** * Checks whether the given subscription is equal to the current instance. * @param other Subscription object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Subscription.prototype.equals = function (other) { return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe; }; /** * Returns a string representation of the current Subscription value. * @returns {String} String representation of the current Subscription value. */ Subscription.prototype.toString = function () { return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')'; }; /** @private */ var MockDisposable = Rx.MockDisposable = function (scheduler) { this.scheduler = scheduler; this.disposes = []; this.disposes.push(this.scheduler.clock); }; /* * @memberOf MockDisposable# * @prviate */ MockDisposable.prototype.dispose = function () { this.disposes.push(this.scheduler.clock); }; /** @private */ var MockObserver = (function (_super) { inherits(MockObserver, _super); /* * @constructor * @prviate */ function MockObserver(scheduler) { _super.call(this); this.scheduler = scheduler; this.messages = []; } var MockObserverPrototype = MockObserver.prototype; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onNext = function (value) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); }; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onError = function (exception) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception))); }; /* * @memberOf MockObserverPrototype# * @prviate */ MockObserverPrototype.onCompleted = function () { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); }; return MockObserver; })(Observer); /** @private */ var HotObservable = (function (_super) { function subscribe(observer) { var observable = this; this.observers.push(observer); this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; return disposableCreate(function () { var idx = observable.observers.indexOf(observer); observable.observers.splice(idx, 1); observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); }); } inherits(HotObservable, _super); /** * @private * @constructor */ function HotObservable(scheduler, messages) { _super.call(this, subscribe); var message, notification, observable = this; this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; this.observers = []; for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { scheduler.scheduleAbsoluteWithState(null, message.time, function () { var obs = observable.observers.slice(0); for (var j = 0, jLen = obs.length; j < jLen; j++) { innerNotification.accept(obs[j]); } return disposableEmpty; }); })(notification); } } return HotObservable; })(Observable); /** @private */ var ColdObservable = (function (_super) { function subscribe(observer) { var message, notification, observable = this; this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; var d = new CompositeDisposable(); for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { d.add(observable.scheduler.scheduleRelativeWithState(null, message.time, function () { innerNotification.accept(observer); return disposableEmpty; })); })(notification); } return disposableCreate(function () { observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); d.dispose(); }); } inherits(ColdObservable, _super); /** * @private * @constructor */ function ColdObservable(scheduler, messages) { _super.call(this, subscribe); this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; } return ColdObservable; })(Observable); /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */ Rx.TestScheduler = (function (_super) { inherits(TestScheduler, _super); function baseComparer(x, y) { return x > y ? 1 : (x < y ? -1 : 0); } /** @constructor */ function TestScheduler() { _super.call(this, 0, baseComparer); } /** * Schedules an action to be executed at the specified virtual time. * * @param state State passed to the action to be executed. * @param dueTime Absolute virtual time at which to execute the action. * @param action Action to be executed. * @return Disposable object used to cancel the scheduled action (best effort). */ TestScheduler.prototype.scheduleAbsoluteWithState = function (state, dueTime, action) { if (dueTime <= this.clock) { dueTime = this.clock + 1; } return _super.prototype.scheduleAbsoluteWithState.call(this, state, dueTime, action); }; /** * Adds a relative virtual time to an absolute virtual time value. * * @param absolute Absolute virtual time value. * @param relative Relative virtual time value to add. * @return Resulting absolute virtual time sum value. */ TestScheduler.prototype.add = function (absolute, relative) { return absolute + relative; }; /** * Converts the absolute virtual time value to a DateTimeOffset value. * * @param absolute Absolute virtual time value to convert. * @return Corresponding DateTimeOffset value. */ TestScheduler.prototype.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @param timeSpan TimeSpan value to convert. * @return Corresponding relative virtual time value. */ TestScheduler.prototype.toRelative = function (timeSpan) { return timeSpan; }; /** * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. * * @param create Factory method to create an observable sequence. * @param created Virtual time at which to invoke the factory to create an observable sequence. * @param subscribed Virtual time at which to subscribe to the created observable sequence. * @param disposed Virtual time at which to dispose the subscription. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithTiming = function (create, created, subscribed, disposed) { var observer = this.createObserver(), source, subscription; this.scheduleAbsoluteWithState(null, created, function () { source = create(); return disposableEmpty; }); this.scheduleAbsoluteWithState(null, subscribed, function () { subscription = source.subscribe(observer); return disposableEmpty; }); this.scheduleAbsoluteWithState(null, disposed, function () { subscription.dispose(); return disposableEmpty; }); this.start(); return observer; }; /** * Starts the test scheduler and uses the specified virtual time to dispose the subscription to the sequence obtained through the factory function. * Default virtual times are used for factory invocation and sequence subscription. * * @param create Factory method to create an observable sequence. * @param disposed Virtual time at which to dispose the subscription. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithDispose = function (create, disposed) { return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, disposed); }; /** * Starts the test scheduler and uses default virtual times to invoke the factory function, to subscribe to the resulting sequence, and to dispose the subscription. * * @param create Factory method to create an observable sequence. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startWithCreate = function (create) { return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, ReactiveTest.disposed); }; /** * Creates a hot observable using the specified timestamped notification messages either as an array or arguments. * * @param messages Notifications to surface through the created sequence at their specified absolute virtual times. * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createHotObservable = function () { var messages = argsOrArray(arguments, 0); return new HotObservable(this, messages); }; /** * Creates a cold observable using the specified timestamped notification messages either as an array or arguments. * * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createColdObservable = function () { var messages = argsOrArray(arguments, 0); return new ColdObservable(this, messages); }; /** * Creates an observer that records received notification messages and timestamps those. * * @return Observer that can be used to assert the timing of received notifications. */ TestScheduler.prototype.createObserver = function () { return new MockObserver(this); }; return TestScheduler; })(VirtualTimeScheduler); return Rx; })); },{"./rx.all":25}],27:[function(require,module,exports){ var Rx = require('./dist/rx.all'); require('./dist/rx.testing'); // Add specific Node functions var EventEmitter = require('events').EventEmitter, Observable = Rx.Observable; Rx.Node = { /** * @deprecated Use Rx.Observable.fromCallback from rx.async.js instead. * * Converts a callback function to an observable sequence. * * @param {Function} func Function to convert to an asynchronous function. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Function} Asynchronous function. */ fromCallback: function (func, context, selector) { return Observable.fromCallback(func, context, selector); }, /** * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. * * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ fromNodeCallback: function (func, context, selector) { return Observable.fromNodeCallback(func, context, selector); }, /** * @deprecated Use Rx.Observable.fromNodeCallback from rx.async.js instead. * * Handles an event from the given EventEmitter as an observable sequence. * * @param {EventEmitter} eventEmitter The EventEmitter to subscribe to the given event. * @param {String} eventName The event name to subscribe * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence generated from the named event from the given EventEmitter. The data will be returned as an array of arguments to the handler. */ fromEvent: function (eventEmitter, eventName, selector) { return Observable.fromEvent(eventEmitter, eventName, selector); }, /** * Converts the given observable sequence to an event emitter with the given event name. * The errors are handled on the 'error' event and completion on the 'end' event. * @param {Observable} observable The observable sequence to convert to an EventEmitter. * @param {String} eventName The event name to emit onNext calls. * @returns {EventEmitter} An EventEmitter which emits the given eventName for each onNext call in addition to 'error' and 'end' events. * You must call publish in order to invoke the subscription on the Observable sequuence. */ toEventEmitter: function (observable, eventName, selector) { var e = new EventEmitter(); // Used to publish the events from the observable e.publish = function () { e.subscription = observable.subscribe( function (x) { var result = x; if (selector) { try { result = selector(x); } catch (e) { e.emit('error', e); return; } } e.emit(eventName, result); }, function (err) { e.emit('error', err); }, function () { e.emit('end'); }); }; return e; }, /** * Converts a flowing stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @param {String} [finishEventName] Event that notifies about closed stream. ("end" by default) * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and finish events like `end` or `finish`. */ fromStream: function (stream, finishEventName) { return Observable.create(function (observer) { function dataHandler (data) { observer.onNext(data); } function errorHandler (err) { observer.onError(err); } function endHandler () { observer.onCompleted(); } if (!finishEventName) { finishEventName = 'end'; } stream.addListener('data', dataHandler); stream.addListener('error', errorHandler); stream.addListener(finishEventName, endHandler); return function () { stream.removeListener('data', dataHandler); stream.removeListener('error', errorHandler); stream.removeListener(finishEventName, endHandler); }; }).publish().refCount(); }, /** * Converts a flowing readable stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'end' events. */ fromReadableStream: function (stream) { return this.fromStream(stream, 'end'); }, /** * Converts a flowing writeable stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'finish' events. */ fromWritableStream: function (stream) { return this.fromStream(stream, 'finish'); }, /** * Converts a flowing transform stream to an Observable sequence. * @param {Stream} stream A stream to convert to a observable sequence. * @returns {Observable} An observable sequence which fires on each 'data' event as well as handling 'error' and 'finish' events. */ fromTransformStream: function (stream) { return this.fromStream(stream, 'finish'); }, /** * Writes an observable sequence to a stream * @param {Observable} observable Observable sequence to write to a stream. * @param {Stream} stream The stream to write to. * @param {String} [encoding] The encoding of the item to write. * @returns {Disposable} The subscription handle. */ writeToStream: function (observable, stream, encoding) { return observable.subscribe( function (x) { stream.write(x, encoding); }, function (err) { stream.emit('error', err); }, function () { // Hack check because STDIO is not closable !stream._isStdio && stream.end(); }); } }; module.exports = Rx; },{"./dist/rx.all":25,"./dist/rx.testing":26,"events":2}],28:[function(require,module,exports){ var createElement = require("vdom/create-element") module.exports = createElement },{"vdom/create-element":32}],29:[function(require,module,exports){ var diff = require("vtree/diff") module.exports = diff },{"vtree/diff":38}],30:[function(require,module,exports){ module.exports = isObject function isObject(x) { return typeof x === "object" && x !== null } },{}],31:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("vtree/is-vhook") module.exports = applyProperties function applyProperties(node, props, previous) { for (var propName in props) { var propValue = props[propName] if (propValue === undefined) { removeProperty(node, props, previous, propName); } else if (isHook(propValue)) { propValue.hook(node, propName, previous ? previous[propName] : undefined) } else { if (isObject(propValue)) { patchObject(node, props, previous, propName, propValue); } else if (propValue !== undefined) { node[propName] = propValue } } } } function removeProperty(node, props, previous, propName) { if (previous) { var previousValue = previous[propName] if (!isHook(previousValue)) { if (propName === "attributes") { for (var attrName in previousValue) { node.removeAttribute(attrName) } } else if (propName === "style") { for (var i in previousValue) { node.style[i] = "" } } else if (typeof previousValue === "string") { node[propName] = "" } else { node[propName] = null } } } } function patchObject(node, props, previous, propName, propValue) { var previousValue = previous ? previous[propName] : undefined // Set attributes if (propName === "attributes") { for (var attrName in propValue) { var attrValue = propValue[attrName] if (attrValue === undefined) { node.removeAttribute(attrName) } else { node.setAttribute(attrName, attrValue) } } return } if(previousValue && isObject(previousValue) && getPrototype(previousValue) !== getPrototype(propValue)) { node[propName] = propValue return } if (!isObject(node[propName])) { node[propName] = {} } var replacer = propName === "style" ? "" : undefined for (var k in propValue) { var value = propValue[k] node[propName][k] = (value === undefined) ? replacer : value } } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"is-object":30,"vtree/is-vhook":41}],32:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") var isVNode = require("vtree/is-vnode") var isVText = require("vtree/is-vtext") var isWidget = require("vtree/is-widget") var handleThunk = require("vtree/handle-thunk") module.exports = createElement function createElement(vnode, opts) { var doc = opts ? opts.document || document : document var warn = opts ? opts.warn : null vnode = handleThunk(vnode).a if (isWidget(vnode)) { return vnode.init() } else if (isVText(vnode)) { return doc.createTextNode(vnode.text) } else if (!isVNode(vnode)) { if (warn) { warn("Item is not a valid virtual dom node", vnode) } return null } var node = (vnode.namespace === null) ? doc.createElement(vnode.tagName) : doc.createElementNS(vnode.namespace, vnode.tagName) var props = vnode.properties applyProperties(node, props) var children = vnode.children for (var i = 0; i < children.length; i++) { var childNode = createElement(children[i], opts) if (childNode) { node.appendChild(childNode) } } return node } },{"./apply-properties":31,"global/document":34,"vtree/handle-thunk":39,"vtree/is-vnode":42,"vtree/is-vtext":43,"vtree/is-widget":44}],33:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. // We only recurse into a DOM node if we know that it contains a child of // interest. var noChild = {} module.exports = domIndex function domIndex(rootNode, tree, indices, nodes) { if (!indices || indices.length === 0) { return {} } else { indices.sort(ascending) return recurse(rootNode, tree, indices, nodes, 0) } } function recurse(rootNode, tree, indices, nodes, rootIndex) { nodes = nodes || {} if (rootNode) { if (indexInRange(indices, rootIndex, rootIndex)) { nodes[rootIndex] = rootNode } var vChildren = tree.children if (vChildren) { var childNodes = rootNode.childNodes for (var i = 0; i < tree.children.length; i++) { rootIndex += 1 var vChild = vChildren[i] || noChild var nextIndex = rootIndex + (vChild.count || 0) // skip recursion down the tree if there are no nodes down here if (indexInRange(indices, rootIndex, nextIndex)) { recurse(childNodes[i], vChild, indices, nodes, rootIndex) } rootIndex = nextIndex } } } return nodes } // Binary search for an index in the interval [left, right] function indexInRange(indices, left, right) { if (indices.length === 0) { return false } var minIndex = 0 var maxIndex = indices.length - 1 var currentIndex var currentItem while (minIndex <= maxIndex) { currentIndex = ((maxIndex + minIndex) / 2) >> 0 currentItem = indices[currentIndex] if (minIndex === maxIndex) { return currentItem >= left && currentItem <= right } else if (currentItem < left) { minIndex = currentIndex + 1 } else if (currentItem > right) { maxIndex = currentIndex - 1 } else { return true } } return false; } function ascending(a, b) { return a > b ? 1 : -1 } },{}],34:[function(require,module,exports){ module.exports=require(14) },{"min-document":4}],35:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("vtree/is-widget") var VPatch = require("vtree/vpatch") var render = require("./create-element") var updateWidget = require("./update-widget") module.exports = applyPatch function applyPatch(vpatch, domNode, renderOptions) { var type = vpatch.type var vNode = vpatch.vNode var patch = vpatch.patch switch (type) { case VPatch.REMOVE: return removeNode(domNode, vNode) case VPatch.INSERT: return insertNode(domNode, patch, renderOptions) case VPatch.VTEXT: return stringPatch(domNode, vNode, patch, renderOptions) case VPatch.WIDGET: return widgetPatch(domNode, vNode, patch, renderOptions) case VPatch.VNODE: return vNodePatch(domNode, vNode, patch, renderOptions) case VPatch.ORDER: reorderChildren(domNode, patch) return domNode case VPatch.PROPS: applyProperties(domNode, patch, vNode.properties) return domNode case VPatch.THUNK: return replaceRoot(domNode, renderOptions.patch(domNode, patch, renderOptions)) default: return domNode } } function removeNode(domNode, vNode) { var parentNode = domNode.parentNode if (parentNode) { parentNode.removeChild(domNode) } destroyWidget(domNode, vNode); return null } function insertNode(parentNode, vNode, renderOptions) { var newNode = render(vNode, renderOptions) if (parentNode) { parentNode.appendChild(newNode) } return parentNode } function stringPatch(domNode, leftVNode, vText, renderOptions) { var newNode if (domNode.nodeType === 3) { domNode.replaceData(0, domNode.length, vText.text) newNode = domNode } else { var parentNode = domNode.parentNode newNode = render(vText, renderOptions) if (parentNode) { parentNode.replaceChild(newNode, domNode) } } destroyWidget(domNode, leftVNode) return newNode } function widgetPatch(domNode, leftVNode, widget, renderOptions) { if (updateWidget(leftVNode, widget)) { return widget.update(leftVNode, domNode) || domNode } var parentNode = domNode.parentNode var newWidget = render(widget, renderOptions) if (parentNode) { parentNode.replaceChild(newWidget, domNode) } destroyWidget(domNode, leftVNode) return newWidget } function vNodePatch(domNode, leftVNode, vNode, renderOptions) { var parentNode = domNode.parentNode var newNode = render(vNode, renderOptions) if (parentNode) { parentNode.replaceChild(newNode, domNode) } destroyWidget(domNode, leftVNode) return newNode } function destroyWidget(domNode, w) { if (typeof w.destroy === "function" && isWidget(w)) { w.destroy(domNode) } } function reorderChildren(domNode, bIndex) { var children = [] var childNodes = domNode.childNodes var len = childNodes.length var i var reverseIndex = bIndex.reverse for (i = 0; i < len; i++) { children.push(domNode.childNodes[i]) } var insertOffset = 0 var move var node var insertNode for (i = 0; i < len; i++) { move = bIndex[i] if (move !== undefined && move !== i) { // the element currently at this index will be moved later so increase the insert offset if (reverseIndex[i] > i) { insertOffset++ } node = children[move] insertNode = childNodes[i + insertOffset] if (node !== insertNode) { domNode.insertBefore(node, insertNode) } // the moved element came from the front of the array so reduce the insert offset if (move < i) { insertOffset-- } } // element at this index is scheduled to be removed so increase insert offset if (i in bIndex.removes) { insertOffset++ } } } function replaceRoot(oldRoot, newRoot) { if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) { console.log(oldRoot) oldRoot.parentNode.replaceChild(newRoot, oldRoot) } return newRoot; } },{"./apply-properties":31,"./create-element":32,"./update-widget":37,"vtree/is-widget":44,"vtree/vpatch":46}],36:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") var domIndex = require("./dom-index") var patchOp = require("./patch-op") module.exports = patch function patch(rootNode, patches) { return patchRecursive(rootNode, patches) } function patchRecursive(rootNode, patches, renderOptions) { var indices = patchIndices(patches) if (indices.length === 0) { return rootNode } var index = domIndex(rootNode, patches.a, indices) var ownerDocument = rootNode.ownerDocument if (!renderOptions) { renderOptions = { patch: patchRecursive } if (ownerDocument !== document) { renderOptions.document = ownerDocument } } for (var i = 0; i < indices.length; i++) { var nodeIndex = indices[i] rootNode = applyPatch(rootNode, index[nodeIndex], patches[nodeIndex], renderOptions) } return rootNode } function applyPatch(rootNode, domNode, patchList, renderOptions) { if (!domNode) { return rootNode } var newNode if (isArray(patchList)) { for (var i = 0; i < patchList.length; i++) { newNode = patchOp(patchList[i], domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } } else { newNode = patchOp(patchList, domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } return rootNode } function patchIndices(patches) { var indices = [] for (var key in patches) { if (key !== "a") { indices.push(Number(key)) } } return indices } },{"./dom-index":33,"./patch-op":35,"global/document":34,"x-is-array":47}],37:[function(require,module,exports){ var isWidget = require("vtree/is-widget") module.exports = updateWidget function updateWidget(a, b) { if (isWidget(a) && isWidget(b)) { if ("name" in a && "name" in b) { return a.id === b.id } else { return a.init === b.init } } return false } },{"vtree/is-widget":44}],38:[function(require,module,exports){ var isArray = require("x-is-array") var isObject = require("is-object") var VPatch = require("./vpatch") var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") var handleThunk = require("./handle-thunk") module.exports = diff function diff(a, b) { var patch = { a: a } walk(a, b, patch, 0) return patch } function walk(a, b, patch, index) { if (a === b) { if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else { hooks(b, patch, index) } return } var apply = patch[index] if (b == null) { apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b)) destroyWidgets(a, patch, index) } else if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else if (isVNode(b)) { if (isVNode(a)) { if (a.tagName === b.tagName && a.namespace === b.namespace && a.key === b.key) { var propsPatch = diffProps(a.properties, b.properties, b.hooks) if (propsPatch) { apply = appendPatch(apply, new VPatch(VPatch.PROPS, a, propsPatch)) } } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) destroyWidgets(a, patch, index) } apply = diffChildren(a, b, patch, apply, index) } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) destroyWidgets(a, patch, index) } } else if (isVText(b)) { if (!isVText(a)) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) destroyWidgets(a, patch, index) } else if (a.text !== b.text) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) } } else if (isWidget(b)) { apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) if (!isWidget(a)) { destroyWidgets(a, patch, index) } } if (apply) { patch[index] = apply } } function diffProps(a, b, hooks) { var diff for (var aKey in a) { if (!(aKey in b)) { diff = diff || {} diff[aKey] = undefined } var aValue = a[aKey] var bValue = b[aKey] if (hooks && aKey in hooks) { diff = diff || {} diff[aKey] = bValue } else { if (isObject(aValue) && isObject(bValue)) { if (getPrototype(bValue) !== getPrototype(aValue)) { diff = diff || {} diff[aKey] = bValue } else { var objectDiff = diffProps(aValue, bValue) if (objectDiff) { diff = diff || {} diff[aKey] = objectDiff } } } else if (aValue !== bValue) { diff = diff || {} diff[aKey] = bValue } } } for (var bKey in b) { if (!(bKey in a)) { diff = diff || {} diff[bKey] = b[bKey] } } return diff } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } function diffChildren(a, b, patch, apply, index) { var aChildren = a.children var bChildren = reorder(aChildren, b.children) var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen for (var i = 0; i < len; i++) { var leftNode = aChildren[i] var rightNode = bChildren[i] index += 1 if (!leftNode) { if (rightNode) { // Excess nodes in b need to be added apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode)) } } else if (!rightNode) { if (leftNode) { // Excess nodes in a need to be removed patch[index] = new VPatch(VPatch.REMOVE, leftNode, null) destroyWidgets(leftNode, patch, index) } } else { walk(leftNode, rightNode, patch, index) } if (isVNode(leftNode) && leftNode.count) { index += leftNode.count } } if (bChildren.moves) { // Reorder nodes last apply = appendPatch(apply, new VPatch(VPatch.ORDER, a, bChildren.moves)) } return apply } // Patch records for all destroyed widgets must be added because we need // a DOM node reference for the destroy function function destroyWidgets(vNode, patch, index) { if (isWidget(vNode)) { if (typeof vNode.destroy === "function") { patch[index] = new VPatch(VPatch.REMOVE, vNode, null) } } else if (isVNode(vNode) && vNode.hasWidgets) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 destroyWidgets(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } // Create a sub-patch for thunks function thunks(a, b, patch, index) { var nodes = handleThunk(a, b); var thunkPatch = diff(nodes.a, nodes.b) if (hasPatches(thunkPatch)) { patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) } } function hasPatches(patch) { for (var index in patch) { if (index !== "a") { return true; } } return false; } // Execute hooks when two nodes are identical function hooks(vNode, patch, index) { if (isVNode(vNode)) { if (vNode.hooks) { patch[index] = new VPatch(VPatch.PROPS, vNode.hooks, vNode.hooks) } if (vNode.descendantHooks) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 hooks(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } } // List diff, naive left to right reordering function reorder(aChildren, bChildren) { var bKeys = keyIndex(bChildren) if (!bKeys) { return bChildren } var aKeys = keyIndex(aChildren) if (!aKeys) { return bChildren } var bMatch = {}, aMatch = {} for (var key in bKeys) { bMatch[bKeys[key]] = aKeys[key] } for (var key in aKeys) { aMatch[aKeys[key]] = bKeys[key] } var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen var shuffle = [] var freeIndex = 0 var i = 0 var moveIndex = 0 var moves = {} var removes = moves.removes = {} var reverse = moves.reverse = {} var hasMoves = false while (freeIndex < len) { var move = aMatch[i] if (move !== undefined) { shuffle[i] = bChildren[move] if (move !== moveIndex) { moves[move] = moveIndex reverse[moveIndex] = move hasMoves = true } moveIndex++ } else if (i in aMatch) { shuffle[i] = undefined removes[i] = moveIndex++ hasMoves = true } else { while (bMatch[freeIndex] !== undefined) { freeIndex++ } if (freeIndex < len) { var freeChild = bChildren[freeIndex] if (freeChild) { shuffle[i] = freeChild if (freeIndex !== moveIndex) { hasMoves = true moves[freeIndex] = moveIndex reverse[moveIndex] = freeIndex } moveIndex++ } freeIndex++ } } i++ } if (hasMoves) { shuffle.moves = moves } return shuffle } function keyIndex(children) { var i, keys for (i = 0; i < children.length; i++) { var child = children[i] if (child.key !== undefined) { keys = keys || {} keys[child.key] = i } } return keys } function appendPatch(apply, patch) { if (apply) { if (isArray(apply)) { apply.push(patch) } else { apply = [apply, patch] } return apply } else { return patch } } },{"./handle-thunk":39,"./is-thunk":40,"./is-vnode":42,"./is-vtext":43,"./is-widget":44,"./vpatch":46,"is-object":30,"x-is-array":47}],39:[function(require,module,exports){ var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") module.exports = handleThunk function handleThunk(a, b) { var renderedA = a var renderedB = b if (isThunk(b)) { renderedB = renderThunk(b, a) } if (isThunk(a)) { renderedA = renderThunk(a, null) } return { a: renderedA, b: renderedB } } function renderThunk(thunk, previous) { var renderedThunk = thunk.vnode if (!renderedThunk) { renderedThunk = thunk.vnode = thunk.render(previous) } if (!(isVNode(renderedThunk) || isVText(renderedThunk) || isWidget(renderedThunk))) { throw new Error("thunk did not return a valid node"); } return renderedThunk } },{"./is-thunk":40,"./is-vnode":42,"./is-vtext":43,"./is-widget":44}],40:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } },{}],41:[function(require,module,exports){ module.exports = isHook function isHook(hook) { return hook && typeof hook.hook === "function" && !hook.hasOwnProperty("hook") } },{}],42:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } },{"./version":45}],43:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } },{"./version":45}],44:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } },{}],45:[function(require,module,exports){ module.exports = "1" },{}],46:[function(require,module,exports){ var version = require("./version") VirtualPatch.NONE = 0 VirtualPatch.VTEXT = 1 VirtualPatch.VNODE = 2 VirtualPatch.WIDGET = 3 VirtualPatch.PROPS = 4 VirtualPatch.ORDER = 5 VirtualPatch.INSERT = 6 VirtualPatch.REMOVE = 7 VirtualPatch.THUNK = 8 module.exports = VirtualPatch function VirtualPatch(type, vNode, patch) { this.type = Number(type) this.vNode = vNode this.patch = patch } VirtualPatch.prototype.version = version VirtualPatch.prototype.type = "VirtualPatch" },{"./version":45}],47:[function(require,module,exports){ var nativeIsArray = Array.isArray var toString = Object.prototype.toString module.exports = nativeIsArray || isArray function isArray(obj) { return toString.call(obj) === "[object Array]" } },{}],48:[function(require,module,exports){ var patch = require("vdom/patch") module.exports = patch },{"vdom/patch":36}],49:[function(require,module,exports){ var DataSet = require("data-set") module.exports = DataSetHook; function DataSetHook(value) { if (!(this instanceof DataSetHook)) { return new DataSetHook(value); } this.value = value; } DataSetHook.prototype.hook = function (node, propertyName) { var ds = DataSet(node) var propName = propertyName.substr(5) ds[propName] = this.value; }; },{"data-set":54}],50:[function(require,module,exports){ var DataSet = require("data-set") module.exports = DataSetHook; function DataSetHook(value) { if (!(this instanceof DataSetHook)) { return new DataSetHook(value); } this.value = value; } DataSetHook.prototype.hook = function (node, propertyName) { var ds = DataSet(node) var propName = propertyName.substr(3) ds[propName] = this.value; }; },{"data-set":54}],51:[function(require,module,exports){ module.exports = SoftSetHook; function SoftSetHook(value) { if (!(this instanceof SoftSetHook)) { return new SoftSetHook(value); } this.value = value; } SoftSetHook.prototype.hook = function (node, propertyName) { if (node[propertyName] !== this.value) { node[propertyName] = this.value; } }; },{}],52:[function(require,module,exports){ var VNode = require("vtree/vnode.js") var VText = require("vtree/vtext.js") var isVNode = require("vtree/is-vnode") var isVText = require("vtree/is-vtext") var isWidget = require("vtree/is-widget") var isHook = require("vtree/is-vhook") var isVThunk = require("vtree/is-thunk") var TypedError = require("error/typed") var parseTag = require("./parse-tag.js") var softSetHook = require("./hooks/soft-set-hook.js") var dataSetHook = require("./hooks/data-set-hook.js") var evHook = require("./hooks/ev-hook.js") var UnexpectedVirtualElement = TypedError({ type: "virtual-hyperscript.unexpected.virtual-element", message: "Unexpected virtual child passed to h().\n" + "Expected a VNode / Vthunk / VWidget / string but:\n" + "got a {foreignObjectStr}.\n" + "The parent vnode is {parentVnodeStr}.\n" + "Suggested fix: change your `h(..., [ ... ])` callsite.", foreignObjectStr: null, parentVnodeStr: null, foreignObject: null, parentVnode: null }) module.exports = h function h(tagName, properties, children) { var childNodes = [] var tag, props, key, namespace if (!children && isChildren(properties)) { children = properties props = {} } props = props || properties || {} tag = parseTag(tagName, props) // support keys if ("key" in props) { key = props.key props.key = undefined } // support namespace if ("namespace" in props) { namespace = props.namespace props.namespace = undefined } // fix cursor bug if (tag === "input" && "value" in props && props.value !== undefined && !isHook(props.value) ) { props.value = softSetHook(props.value) } var keys = Object.keys(props) var propName, value for (var j = 0; j < keys.length; j++) { propName = keys[j] value = props[propName] if (isHook(value)) { continue } // add data-foo support if (propName.substr(0, 5) === "data-") { props[propName] = dataSetHook(value) } // add ev-foo support if (propName.substr(0, 3) === "ev-") { props[propName] = evHook(value) } } if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props) } var node = new VNode(tag, props, childNodes, key, namespace) return node } function addChild(c, childNodes, tag, props) { if (typeof c === "string") { childNodes.push(new VText(c)) } else if (isChild(c)) { childNodes.push(c) } else if (Array.isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props) } } else if (c === null || c === undefined) { return } else { throw UnexpectedVirtualElement({ foreignObjectStr: JSON.stringify(c), foreignObject: c, parentVnodeStr: JSON.stringify({ tagName: tag, properties: props }), parentVnode: { tagName: tag, properties: props } }) } } function isChild(x) { return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x) } function isChildren(x) { return typeof x === "string" || Array.isArray(x) || isChild(x) } },{"./hooks/data-set-hook.js":49,"./hooks/ev-hook.js":50,"./hooks/soft-set-hook.js":51,"./parse-tag.js":70,"error/typed":61,"vtree/is-thunk":62,"vtree/is-vhook":63,"vtree/is-vnode":64,"vtree/is-vtext":65,"vtree/is-widget":66,"vtree/vnode.js":68,"vtree/vtext.js":69}],53:[function(require,module,exports){ module.exports=require(10) },{}],54:[function(require,module,exports){ arguments[4][11][0].apply(exports,arguments) },{"./create-hash.js":53,"individual":55,"weakmap-shim/create-store":56}],55:[function(require,module,exports){ module.exports=require(15) },{}],56:[function(require,module,exports){ module.exports=require(12) },{"./hidden-store.js":57}],57:[function(require,module,exports){ module.exports=require(13) },{}],58:[function(require,module,exports){ module.exports = function(obj) { if (typeof obj === 'string') return camelCase(obj); return walk(obj); }; function walk (obj) { if (!obj || typeof obj !== 'object') return obj; if (isDate(obj) || isRegex(obj)) return obj; if (isArray(obj)) return map(obj, walk); return reduce(objectKeys(obj), function (acc, key) { var camel = camelCase(key); acc[camel] = walk(obj[key]); return acc; }, {}); } function camelCase(str) { return str.replace(/[_.-](\w|$)/g, function (_,x) { return x.toUpperCase(); }); } var isArray = Array.isArray || function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; var isDate = function (obj) { return Object.prototype.toString.call(obj) === '[object Date]'; }; var isRegex = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var has = Object.prototype.hasOwnProperty; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } function reduce (xs, f, acc) { if (xs.reduce) return xs.reduce(f, acc); for (var i = 0; i < xs.length; i++) { acc = f(acc, xs[i], i); } return acc; } },{}],59:[function(require,module,exports){ var nargs = /\{([0-9a-zA-Z]+)\}/g var slice = Array.prototype.slice module.exports = template function template(string) { var args if (arguments.length === 2 && typeof arguments[1] === "object") { args = arguments[1] } else { args = slice.call(arguments, 1) } if (!args || !args.hasOwnProperty) { args = {} } return string.replace(nargs, function replaceArg(match, i, index) { var result if (string[index - 1] === "{" && string[index + match.length] === "}") { return i } else { result = args.hasOwnProperty(i) ? args[i] : null if (result === null || result === undefined) { return "" } return result } }) } },{}],60:[function(require,module,exports){ module.exports = extend function extend(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } },{}],61:[function(require,module,exports){ var camelize = require("camelize") var template = require("string-template") var extend = require("xtend/mutable") module.exports = TypedError function TypedError(args) { if (!args) { throw new Error("args is required"); } if (!args.type) { throw new Error("args.type is required"); } if (!args.message) { throw new Error("args.message is required"); } var message = args.message if (args.type && !args.name) { var errorName = camelize(args.type) + "Error" args.name = errorName[0].toUpperCase() + errorName.substr(1) } createError.type = args.type; createError._name = args.name; return createError; function createError(opts) { var result = new Error() Object.defineProperty(result, "type", { value: result.type, enumerable: true, writable: true, configurable: true }) var options = extend({}, args, opts) extend(result, options) result.message = template(message, options) return result } } },{"camelize":58,"string-template":59,"xtend/mutable":60}],62:[function(require,module,exports){ module.exports=require(40) },{}],63:[function(require,module,exports){ module.exports=require(41) },{}],64:[function(require,module,exports){ module.exports=require(42) },{"./version":67}],65:[function(require,module,exports){ module.exports=require(43) },{"./version":67}],66:[function(require,module,exports){ module.exports=require(44) },{}],67:[function(require,module,exports){ module.exports=require(45) },{}],68:[function(require,module,exports){ var version = require("./version") var isVNode = require("./is-vnode") var isWidget = require("./is-widget") var isVHook = require("./is-vhook") module.exports = VirtualNode var noProperties = {} var noChildren = [] function VirtualNode(tagName, properties, children, key, namespace) { this.tagName = tagName this.properties = properties || noProperties this.children = children || noChildren this.key = key != null ? String(key) : undefined this.namespace = (typeof namespace === "string") ? namespace : null var count = (children && children.length) || 0 var descendants = 0 var hasWidgets = false var descendantHooks = false var hooks for (var propName in properties) { if (properties.hasOwnProperty(propName)) { var property = properties[propName] if (isVHook(property)) { if (!hooks) { hooks = {} } hooks[propName] = property } } } for (var i = 0; i < count; i++) { var child = children[i] if (isVNode(child)) { descendants += child.count || 0 if (!hasWidgets && child.hasWidgets) { hasWidgets = true } if (!descendantHooks && (child.hooks || child.descendantHooks)) { descendantHooks = true } } else if (!hasWidgets && isWidget(child)) { if (typeof child.destroy === "function") { hasWidgets = true } } } this.count = count + descendants this.hasWidgets = hasWidgets this.hooks = hooks this.descendantHooks = descendantHooks } VirtualNode.prototype.version = version VirtualNode.prototype.type = "VirtualNode" },{"./is-vhook":63,"./is-vnode":64,"./is-widget":66,"./version":67}],69:[function(require,module,exports){ var version = require("./version") module.exports = VirtualText function VirtualText(text) { this.text = String(text) } VirtualText.prototype.version = version VirtualText.prototype.type = "VirtualText" },{"./version":67}],70:[function(require,module,exports){ var classIdSplit = /([\.#]?[a-zA-Z0-9_:-]+)/ var notClassId = /^\.|#/ module.exports = parseTag function parseTag(tag, props) { if (!tag) { return "div" } var noId = !("id" in props) var tagParts = tag.split(classIdSplit) var tagName = null if (notClassId.test(tagParts[1])) { tagName = "div" } var classes, part, type, i for (i = 0; i < tagParts.length; i++) { part = tagParts[i] if (!part) { continue } type = part.charAt(0) if (!tagName) { tagName = part } else if (type === ".") { classes = classes || [] classes.push(part.substring(1, part.length)) } else if (type === "#" && noId) { props.id = part.substring(1, part.length) } } if (classes) { if (props.className) { classes.push(props.className) } props.className = classes.join(" ") } return tagName ? tagName.toLowerCase() : "div" } },{}],71:[function(require,module,exports){ 'use strict'; var binder = require('mvi-example/utils/binder'); var renderer = require('mvi-example/renderer'); var ItemsModel = require('mvi-example/models/items'); var ItemsView = require('mvi-example/views/items'); var ItemsIntent = require('mvi-example/intents/items'); window.onload = function () { binder(ItemsModel, ItemsView, ItemsIntent); renderer.init(); }; },{"mvi-example/intents/items":19,"mvi-example/models/items":20,"mvi-example/renderer":21,"mvi-example/utils/binder":22,"mvi-example/views/items":24}]},{},[71]) ;
Compiled browserify
dist/js/app.js
Compiled browserify
<ide><path>ist/js/app.js <ide> operation: 'changeColor', <ide> id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), <ide> color: inputEvent.currentTarget.value <del> } <add> }; <ide> }); <ide> <ide> var widthChanged$ = inputItemWidthChanged$ <ide> operation: 'changeWidth', <ide> id: Number(inputEvent.currentTarget.attributes['data-item-id'].value), <ide> width: Number(inputEvent.currentTarget.value) <del> } <add> }; <ide> }); <ide> <ide> module.exports = { <ide> <ide> function renderVTreeStream(vtree$, containerSelector) { <ide> // Find and prepare the container <del> var container = document.querySelector(containerSelector); <add> var container = window.document.querySelector(containerSelector); <ide> if (container === null) { <ide> console.error('Couldn\'t render into unknown \'' + containerSelector + '\''); <ide> return false; <ide> } <ide> container.innerHTML = ''; <ide> // Make the DOM node bound to the VDOM node <del> var rootNode = document.createElement('div'); <add> var rootNode = window.document.createElement('div'); <ide> container.appendChild(rootNode); <ide> vtree$.startWith(h()) <ide> .bufferWithCount(2, 1)
Java
apache-2.0
184483359b017d23a41c1eaa22b591ad07716b46
0
shils/groovy,paulk-asert/incubator-groovy,shils/incubator-groovy,apache/incubator-groovy,russel/groovy,traneHead/groovy-core,russel/incubator-groovy,paulk-asert/groovy,shils/incubator-groovy,apache/incubator-groovy,apache/groovy,paulk-asert/incubator-groovy,russel/incubator-groovy,paulk-asert/incubator-groovy,shils/groovy,jwagenleitner/incubator-groovy,russel/groovy,armsargis/groovy,apache/incubator-groovy,armsargis/groovy,russel/groovy,jwagenleitner/incubator-groovy,apache/groovy,shils/groovy,paulk-asert/groovy,shils/incubator-groovy,traneHead/groovy-core,jwagenleitner/groovy,jwagenleitner/incubator-groovy,jwagenleitner/groovy,traneHead/groovy-core,paulk-asert/groovy,paulk-asert/groovy,apache/groovy,russel/groovy,shils/incubator-groovy,apache/groovy,jwagenleitner/groovy,jwagenleitner/incubator-groovy,armsargis/groovy,armsargis/groovy,shils/groovy,paulk-asert/incubator-groovy,russel/incubator-groovy,jwagenleitner/groovy,apache/incubator-groovy,russel/incubator-groovy,paulk-asert/incubator-groovy,traneHead/groovy-core
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.ast.tools; import groovy.transform.Generated; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import java.util.List; /** * Utility class for working with AnnotatedNodes */ public class AnnotatedNodeUtils { private static final ClassNode GENERATED_TYPE = ClassHelper.make(Generated.class); private AnnotatedNodeUtils() { } public static void markAsGenerated(ClassNode containingClass, AnnotatedNode nodeToMark) { boolean shouldAnnotate = containingClass.getModule() != null && containingClass.getModule().getContext() != null; if (shouldAnnotate && !hasAnnotation(nodeToMark, GENERATED_TYPE)) { nodeToMark.addAnnotation(new AnnotationNode(GENERATED_TYPE)); } } public static boolean hasAnnotation(AnnotatedNode node, ClassNode annotation) { List annots = node.getAnnotations(annotation); return (annots != null && !annots.isEmpty()); } }
src/main/java/org/apache/groovy/ast/tools/AnnotatedNodeUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.groovy.ast.tools; import groovy.transform.Generated; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import java.util.List; /** * Utility class for working with AnnotatedNodes */ public class AnnotatedNodeUtils { private static final ClassNode GENERATED_TYPE = ClassHelper.make(Generated.class); private AnnotatedNodeUtils() { } public static void markAsGenerated(ClassNode containingClass, AnnotatedNode nodeToMark) { boolean shouldAnnotate = containingClass.getModule() != null && containingClass.getModule().getContext() != null; if (shouldAnnotate) { nodeToMark.addAnnotation(new AnnotationNode(GENERATED_TYPE)); } } public static boolean hasAnnotation(AnnotatedNode node, ClassNode annotation) { List annots = node.getAnnotations(annotation); return (annots != null && !annots.isEmpty()); } }
GROOVY-8822: Conflict between @Generated and @Delegate (add an extra guard)
src/main/java/org/apache/groovy/ast/tools/AnnotatedNodeUtils.java
GROOVY-8822: Conflict between @Generated and @Delegate (add an extra guard)
<ide><path>rc/main/java/org/apache/groovy/ast/tools/AnnotatedNodeUtils.java <ide> <ide> public static void markAsGenerated(ClassNode containingClass, AnnotatedNode nodeToMark) { <ide> boolean shouldAnnotate = containingClass.getModule() != null && containingClass.getModule().getContext() != null; <del> if (shouldAnnotate) { <add> if (shouldAnnotate && !hasAnnotation(nodeToMark, GENERATED_TYPE)) { <ide> nodeToMark.addAnnotation(new AnnotationNode(GENERATED_TYPE)); <ide> } <ide> }
Java
apache-2.0
394985d5b3fb0441ad9fa5efb49835243b2dfc91
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.shardingjdbc.executor; import lombok.SneakyThrows; import org.apache.shardingsphere.core.constant.ConnectionMode; import org.apache.shardingsphere.core.constant.SQLType; import org.apache.shardingsphere.core.executor.ShardingExecuteGroup; import org.apache.shardingsphere.core.executor.StatementExecuteUnit; import org.apache.shardingsphere.core.merger.QueryResult; import org.apache.shardingsphere.core.routing.RouteUnit; import org.apache.shardingsphere.core.routing.SQLUnit; import org.junit.Test; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTest { private static final String DQL_SQL = "SELECT * FROM table_x"; private static final String DML_SQL = "DELETE FROM table_x"; private PreparedStatementExecutor actual; @Override public void setUp() throws SQLException { super.setUp(); actual = spy(new PreparedStatementExecutor(1, 1, 1, false, getConnection())); doReturn(true).when(actual).isAccumulate(); } @Test public void assertNoStatement() throws SQLException { assertFalse(actual.execute()); assertThat(actual.executeUpdate(), is(0)); assertThat(actual.executeQuery().size(), is(0)); } @Test public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); ResultSet resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet.getString(1)).thenReturn("value"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(preparedStatement.executeQuery()).thenReturn(resultSet); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertThat((String) actual.executeQuery().iterator().next().getValue(1, String.class), is("decryptValue")); } private PreparedStatement getPreparedStatement() throws SQLException { PreparedStatement statement = mock(PreparedStatement.class); Connection connection = mock(Connection.class); DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class); when(databaseMetaData.getURL()).thenReturn("jdbc:h2:mem:ds_master;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL"); when(connection.getMetaData()).thenReturn(databaseMetaData); when(statement.getConnection()).thenReturn(connection); return statement; } @Test public void assertExecuteQueryForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); ResultSet resultSet1 = mock(ResultSet.class); ResultSet resultSet2 = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); when(resultSet2.getMetaData()).thenReturn(resultSetMetaData); when(resultSet1.getInt(1)).thenReturn(1); when(resultSet2.getInt(1)).thenReturn(2); when(preparedStatement1.executeQuery()).thenReturn(resultSet1); when(preparedStatement2.executeQuery()).thenReturn(resultSet2); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); List<QueryResult> result = actual.executeQuery(); for (QueryResult each : result) { assertThat(String.valueOf(each.getValue(1, int.class)), is("decryptValue")); } verify(preparedStatement1).executeQuery(); verify(preparedStatement2).executeQuery(); } @Test public void assertExecuteQueryForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeQuery()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertThat(actual.executeQuery(), is(Collections.singletonList((QueryResult) null))); verify(preparedStatement).executeQuery(); } @Test public void assertExecuteQueryForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.executeQuery()).thenThrow(exp); when(preparedStatement2.executeQuery()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); List<QueryResult> actualResultSets = actual.executeQuery(); assertThat(actualResultSets, is(Arrays.asList((QueryResult) null, null))); verify(preparedStatement1).executeQuery(); verify(preparedStatement2).executeQuery(); } @Test public void assertExecuteUpdateForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.executeUpdate()).thenReturn(10); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertThat(actual.executeUpdate(), is(10)); verify(preparedStatement).executeUpdate(); } @Test public void assertExecuteUpdateForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.executeUpdate()).thenReturn(10); when(preparedStatement2.executeUpdate()).thenReturn(20); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertThat(actual.executeUpdate(), is(30)); verify(preparedStatement1).executeUpdate(); verify(preparedStatement2).executeUpdate(); } @Test public void assertExecuteUpdateForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeUpdate()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertThat(actual.executeUpdate(), is(0)); verify(preparedStatement).executeUpdate(); } @Test public void assertExecuteUpdateForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.executeUpdate()).thenThrow(exp); when(preparedStatement2.executeUpdate()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertThat(actual.executeUpdate(), is(0)); verify(preparedStatement1).executeUpdate(); verify(preparedStatement2).executeUpdate(); } @Test public void assertExecuteForSinglePreparedStatementSuccessWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(false); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatementsSuccessWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(false); when(preparedStatement2.execute()).thenReturn(false); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @Test public void assertExecuteForSinglePreparedStatementFailureWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.execute()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatementsFailureWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.execute()).thenThrow(exp); when(preparedStatement2.execute()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @Test public void assertExecuteForSinglePreparedStatementWithDQL() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(true); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertTrue(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatements() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(true); when(preparedStatement2.execute()).thenReturn(true); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); assertTrue(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @SneakyThrows private void setExecuteGroups(final List<PreparedStatement> preparedStatements, final SQLType sqlType) { Collection<ShardingExecuteGroup<StatementExecuteUnit>> executeGroups = new LinkedList<>(); List<StatementExecuteUnit> preparedStatementExecuteUnits = new LinkedList<>(); executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); for (PreparedStatement each : preparedStatements) { List<List<Object>> parameterSets = new LinkedList<>(); String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; parameterSets.add(Collections.singletonList((Object) 1)); preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); } Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); field.setAccessible(true); field.set(actual, executeGroups); } }
sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.shardingjdbc.executor; import lombok.SneakyThrows; import org.apache.shardingsphere.core.constant.ConnectionMode; import org.apache.shardingsphere.core.constant.SQLType; import org.apache.shardingsphere.core.executor.ShardingExecuteGroup; import org.apache.shardingsphere.core.executor.StatementExecuteUnit; import org.apache.shardingsphere.core.merger.QueryResult; import org.apache.shardingsphere.core.routing.RouteUnit; import org.apache.shardingsphere.core.routing.SQLUnit; import org.junit.Test; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTest { private static final String DQL_SQL = "SELECT * FROM table_x"; private static final String DML_SQL = "DELETE FROM table_x"; private PreparedStatementExecutor actual; @Override public void setUp() throws SQLException { super.setUp(); actual = spy(new PreparedStatementExecutor(1, 1, 1, false, getConnection())); doReturn(true).when(actual).isAccumulate(); } @Test public void assertNoStatement() throws SQLException { assertFalse(actual.execute()); assertThat(actual.executeUpdate(), is(0)); assertThat(actual.executeQuery().size(), is(0)); } @Test public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); ResultSet resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet.getString(1)).thenReturn("value"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(preparedStatement.executeQuery()).thenReturn(resultSet); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertThat((String) actual.executeQuery().iterator().next().getValue(1, String.class), is("decryptValue")); } private PreparedStatement getPreparedStatement() throws SQLException { PreparedStatement statement = mock(PreparedStatement.class); Connection connection = mock(Connection.class); DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class); when(databaseMetaData.getURL()).thenReturn("jdbc:h2:mem:ds_master;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL"); when(connection.getMetaData()).thenReturn(databaseMetaData); when(statement.getConnection()).thenReturn(connection); return statement; } @Test public void assertExecuteQueryForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); ResultSet resultSet1 = mock(ResultSet.class); ResultSet resultSet2 = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); when(resultSet2.getMetaData()).thenReturn(resultSetMetaData); when(resultSet1.getInt(1)).thenReturn(1); when(resultSet2.getInt(1)).thenReturn(2); when(preparedStatement1.executeQuery()).thenReturn(resultSet1); when(preparedStatement2.executeQuery()).thenReturn(resultSet2); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); List<QueryResult> result = actual.executeQuery(); for (QueryResult aResult : result) { assertThat(String.valueOf(aResult.getValue(1, int.class)), is("decryptValue")); } verify(preparedStatement1).executeQuery(); verify(preparedStatement2).executeQuery(); } @Test public void assertExecuteQueryForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeQuery()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertThat(actual.executeQuery(), is(Collections.singletonList((QueryResult) null))); verify(preparedStatement).executeQuery(); } @Test public void assertExecuteQueryForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.executeQuery()).thenThrow(exp); when(preparedStatement2.executeQuery()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); List<QueryResult> actualResultSets = actual.executeQuery(); assertThat(actualResultSets, is(Arrays.asList((QueryResult) null, null))); verify(preparedStatement1).executeQuery(); verify(preparedStatement2).executeQuery(); } @Test public void assertExecuteUpdateForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.executeUpdate()).thenReturn(10); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertThat(actual.executeUpdate(), is(10)); verify(preparedStatement).executeUpdate(); } @Test public void assertExecuteUpdateForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.executeUpdate()).thenReturn(10); when(preparedStatement2.executeUpdate()).thenReturn(20); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertThat(actual.executeUpdate(), is(30)); verify(preparedStatement1).executeUpdate(); verify(preparedStatement2).executeUpdate(); } @Test public void assertExecuteUpdateForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeUpdate()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertThat(actual.executeUpdate(), is(0)); verify(preparedStatement).executeUpdate(); } @Test public void assertExecuteUpdateForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.executeUpdate()).thenThrow(exp); when(preparedStatement2.executeUpdate()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertThat(actual.executeUpdate(), is(0)); verify(preparedStatement1).executeUpdate(); verify(preparedStatement2).executeUpdate(); } @Test public void assertExecuteForSinglePreparedStatementSuccessWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(false); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatementsSuccessWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(false); when(preparedStatement2.execute()).thenReturn(false); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @Test public void assertExecuteForSinglePreparedStatementFailureWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.execute()).thenThrow(exp); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatementsFailureWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement1.execute()).thenThrow(exp); when(preparedStatement2.execute()).thenThrow(exp); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DML); assertFalse(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @Test public void assertExecuteForSinglePreparedStatementWithDQL() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(true); setExecuteGroups(Collections.singletonList(preparedStatement), SQLType.DQL); assertTrue(actual.execute()); verify(preparedStatement).execute(); } @Test public void assertExecuteForMultiplePreparedStatements() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(true); when(preparedStatement2.execute()).thenReturn(true); setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); assertTrue(actual.execute()); verify(preparedStatement1).execute(); verify(preparedStatement2).execute(); } @SneakyThrows private void setExecuteGroups(final List<PreparedStatement> preparedStatements, final SQLType sqlType) { Collection<ShardingExecuteGroup<StatementExecuteUnit>> executeGroups = new LinkedList<>(); List<StatementExecuteUnit> preparedStatementExecuteUnits = new LinkedList<>(); executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); for (PreparedStatement each : preparedStatements) { List<List<Object>> parameterSets = new LinkedList<>(); String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; parameterSets.add(Collections.singletonList((Object) 1)); preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); } Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); field.setAccessible(true); field.set(actual, executeGroups); } }
use each
sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java
use each
<ide><path>harding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java <ide> when(preparedStatement2.executeQuery()).thenReturn(resultSet2); <ide> setExecuteGroups(Arrays.asList(preparedStatement1, preparedStatement2), SQLType.DQL); <ide> List<QueryResult> result = actual.executeQuery(); <del> for (QueryResult aResult : result) { <del> assertThat(String.valueOf(aResult.getValue(1, int.class)), is("decryptValue")); <add> for (QueryResult each : result) { <add> assertThat(String.valueOf(each.getValue(1, int.class)), is("decryptValue")); <ide> } <ide> verify(preparedStatement1).executeQuery(); <ide> verify(preparedStatement2).executeQuery();
Java
apache-2.0
27c6f040da5d395129f0406def96dfa74531be6c
0
infinispan/protostream
package org.infinispan.protostream.annotations.impl.processor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.processing.Filer; import javax.annotation.processing.FilerException; import javax.lang.model.element.Element; import javax.tools.FileObject; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; /** * Tracks generated source files. Also keeps track of which files are 'disabled', ie. generated due to dependency * processing, but are not part of current module and do not need to be actually emitted and compiled. * * @author [email protected] * @since 4.3 */ final class GeneratedFilesWriter { private final Map<String, GeneratedFile> generatedFiles = new LinkedHashMap<>(); interface GeneratedFile { /** * Will it be written on disk (true) or is it just a memory-only file (false)? */ boolean isEnabled(); String getSource(); void write(Filer filer) throws IOException; } private static final class SourceFile implements GeneratedFile { private final boolean isEnabled; private final String className; private final String source; private final Element[] originatingElements; SourceFile(boolean isEnabled, String className, String source, Element... originatingElements) { this.isEnabled = isEnabled; this.className = className; this.source = source; this.originatingElements = originatingElements; } @Override public boolean isEnabled() { return isEnabled; } @Override public String getSource() { return source; } @Override public void write(Filer filer) throws IOException { // check disk contents before writing the generated file again to avoid causing needless rebuilds if (checkSourceFileUpToDate(filer, className, source)) { return; } JavaFileObject file; try { file = filer.createSourceFile(className, originatingElements); } catch (FilerException fe) { // duplicated class name maybe throw new AnnotationProcessingException(fe, originatingElements[0], "%s", fe.getMessage()); } try (PrintWriter out = new PrintWriter(file.openWriter())) { out.print(source); } } } private static final class ResourceFile implements GeneratedFile { private final boolean isEnabled; // file name relative to root package private final String fileName; private final String source; private final Element[] originatingElements; ResourceFile(boolean isEnabled, String fileName, String source, Element... originatingElements) { this.isEnabled = isEnabled; this.fileName = fileName.startsWith("/") ? fileName.substring(1) : fileName; this.source = source; this.originatingElements = originatingElements; } @Override public boolean isEnabled() { return isEnabled; } @Override public String getSource() { return source; } @Override public void write(Filer filer) throws IOException { // check disk contents before writing the generated file again to avoid causing needless rebuilds if (checkResourceFileUpToDate(filer, fileName, source)) { return; } FileObject file; try { file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName, originatingElements); } catch (FilerException e) { throw new AnnotationProcessingException(e, originatingElements[0], "Failed to create resource file \"%s\". Name could be invalid or the file already exists?", fileName); } try (PrintWriter out = new PrintWriter(file.openWriter())) { out.print(source); } } } private final Filer filer; private boolean isEnabled = true; GeneratedFilesWriter(Filer filer) { this.filer = filer; } public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public void addMarshallerSourceFile(String className, String source, Element originatingElement) throws IOException { addGeneratedFile(className, new SourceFile(isEnabled, className, source, originatingElement)); } public void addInitializerSourceFile(String className, String source, Element[] originatingElements) throws IOException { addGeneratedFile(className, new SourceFile(isEnabled, className, source, originatingElements)); } public void addSchemaResourceFile(String fileName, String source, Element[] originatingElements) throws IOException { addGeneratedFile(fileName, new ResourceFile(isEnabled, fileName, source, originatingElements)); } private void addGeneratedFile(String fqn, GeneratedFile file) throws IOException { boolean doWrite = true; GeneratedFile existingFile = generatedFiles.get(fqn); if (existingFile != null) { // check in-memory contents if (!file.getSource().equals(existingFile.getSource())) { throw new IllegalStateException("File " + fqn + " was generated twice with different contents."); } doWrite = !existingFile.isEnabled() && isEnabled; } if (doWrite) { generatedFiles.put(fqn, file); if (isEnabled) { file.write(filer); } } } /** * Checks that a generated resource file exists on disk and the contents matches the expected string. * * @param filer the Filer * @param fileName the file name * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise */ private static boolean checkResourceFileUpToDate(Filer filer, String fileName, String contents) { try { FileObject resourceFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", fileName); try (InputStream is = resourceFile.openInputStream()) { String existing = readUtf8String(is); return contents.equals(existing); } } catch (IOException e) { return false; } } /** * Checks that a generated source file is up to date: it exists on disk, the contents matches the expected string and * the corresponding class also exists and its timestamp is newer. * * @param filer the Filer * @param className fully qualified class name * @param contents the expected contents of the source file * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise */ private static boolean checkSourceFileUpToDate(Filer filer, String className, String contents) { String fileName = className.replace('.', '/'); long sourceTimestamp; try { FileObject javaFile = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", fileName + ".java"); try (InputStream is = javaFile.openInputStream()) { String existing = readUtf8String(is); if (!contents.equals(existing)) { return false; } } sourceTimestamp = javaFile.getLastModified(); } catch (IOException e) { return false; } long classTimestamp; try { FileObject classFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", fileName + ".class"); classTimestamp = classFile.getLastModified(); } catch (IOException e) { return false; } return sourceTimestamp <= classTimestamp; } //todo [anistor] we assume that our source/resource files are all UTF-8 private static String readUtf8String(InputStream is) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) != -1) { bytes.write(buf, 0, len); } return bytes.toString(StandardCharsets.UTF_8.name()); } }
processor/src/main/java/org/infinispan/protostream/annotations/impl/processor/GeneratedFilesWriter.java
package org.infinispan.protostream.annotations.impl.processor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.processing.Filer; import javax.annotation.processing.FilerException; import javax.lang.model.element.Element; import javax.tools.FileObject; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; /** * Tracks generated source files. Also keeps track of which files are 'disabled', ie. generated due to dependency * processing, but are not part of current module and do not need to be actually emitted and compiled. * * @author [email protected] * @since 4.3 */ final class GeneratedFilesWriter { private final Map<String, GeneratedFile> generatedFiles = new LinkedHashMap<>(); interface GeneratedFile { /** * Will it be written on disk (true) or is it just a memory-only file (false)? */ boolean isEnabled(); String getSource(); void write(Filer filer) throws IOException; } private static final class SourceFile implements GeneratedFile { private final boolean isEnabled; private final String className; private final String source; private final Element[] originatingElements; SourceFile(boolean isEnabled, String className, String source, Element... originatingElements) { this.isEnabled = isEnabled; this.className = className; this.source = source; this.originatingElements = originatingElements; } @Override public boolean isEnabled() { return isEnabled; } @Override public String getSource() { return source; } @Override public void write(Filer filer) throws IOException { // check disk contents if (source.equals(getSourceFileContents(filer, className))) { return; } JavaFileObject file; try { file = filer.createSourceFile(className, originatingElements); } catch (FilerException fe) { // duplicated class name maybe throw new AnnotationProcessingException(fe, originatingElements[0], "%s", fe.getMessage()); } try (PrintWriter out = new PrintWriter(file.openWriter())) { out.print(source); } } } private static final class ResourceFile implements GeneratedFile { private final boolean isEnabled; // file name relative to root package private final String fileName; private final String source; private final Element[] originatingElements; ResourceFile(boolean isEnabled, String fileName, String source, Element... originatingElements) { this.isEnabled = isEnabled; this.fileName = fileName.startsWith("/") ? fileName.substring(1) : fileName; this.source = source; this.originatingElements = originatingElements; } @Override public boolean isEnabled() { return isEnabled; } @Override public String getSource() { return source; } @Override public void write(Filer filer) throws IOException { // check disk contents if (source.equals(getResourceFileContents(filer, "", fileName))) { return; } FileObject file; try { file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName, originatingElements); } catch (FilerException e) { throw new AnnotationProcessingException(e, originatingElements[0], "Failed to create resource file \"%s\". Name could be invalid or the file already exists?", fileName); } try (PrintWriter out = new PrintWriter(file.openWriter())) { out.print(source); } } } private final Filer filer; private boolean isEnabled = true; GeneratedFilesWriter(Filer filer) { this.filer = filer; } public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public void addMarshallerSourceFile(String className, String source, Element originatingElement) throws IOException { addGeneratedFile(className, new SourceFile(isEnabled, className, source, originatingElement)); } public void addInitializerSourceFile(String className, String source, Element[] originatingElements) throws IOException { addGeneratedFile(className, new SourceFile(isEnabled, className, source, originatingElements)); } public void addSchemaResourceFile(String fileName, String source, Element[] originatingElements) throws IOException { addGeneratedFile(fileName, new ResourceFile(isEnabled, fileName, source, originatingElements)); } private void addGeneratedFile(String fqn, GeneratedFile file) throws IOException { boolean doWrite = true; GeneratedFile existingFile = generatedFiles.get(fqn); if (existingFile != null) { // check in-memory contents if (!file.getSource().equals(existingFile.getSource())) { throw new IllegalStateException("File " + fqn + " was generated twice with different contents."); } doWrite = !existingFile.isEnabled() && isEnabled; } if (doWrite) { generatedFiles.put(fqn, file); if (isEnabled) { file.write(filer); } } } /** * Reads the contents of a generated resource file if it exists. * * @param filer the Filer * @param pkg package relative to which the file should be searched, or the empty string if none * @param relativeName final pathname components of the file * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise * @throws IOException if there is an I/O error during reading of file contents */ private static String getResourceFileContents(Filer filer, String pkg, String relativeName) throws IOException { InputStream is; try { is = filer.getResource(StandardLocation.CLASS_OUTPUT, pkg, relativeName).openInputStream(); } catch (IOException e) { return null; } try { return readUtf8String(is); } finally { is.close(); } } /** * Reads the contents of a generated source file if it exists. * * @param filer the Filer * @param className fully qualified class name * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise * @throws IOException if there is an I/O error during reading of file contents */ private static String getSourceFileContents(Filer filer, String className) throws IOException { InputStream is; try { is = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", className.replace('.', '/') + ".java").openInputStream(); } catch (IOException e) { return null; } try { return readUtf8String(is); } finally { is.close(); } } //todo [anistor] we assume that our source/resource files are all UTF-8 private static String readUtf8String(InputStream is) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) != -1) { bytes.write(buf, 0, len); } return bytes.toString(StandardCharsets.UTF_8.name()); } }
IPROTO-161 Enhance generated source file up-to-date check by also ensuring the class file exists and is newer that the java file * Maven compiler plugin 3.8.1 and Protostream seem broken, see comments here: https://issues.jboss.org/browse/IPROTO-161
processor/src/main/java/org/infinispan/protostream/annotations/impl/processor/GeneratedFilesWriter.java
IPROTO-161 Enhance generated source file up-to-date check by also ensuring the class file exists and is newer that the java file
<ide><path>rocessor/src/main/java/org/infinispan/protostream/annotations/impl/processor/GeneratedFilesWriter.java <ide> <ide> @Override <ide> public void write(Filer filer) throws IOException { <del> // check disk contents <del> if (source.equals(getSourceFileContents(filer, className))) { <add> // check disk contents before writing the generated file again to avoid causing needless rebuilds <add> if (checkSourceFileUpToDate(filer, className, source)) { <ide> return; <ide> } <ide> <ide> <ide> @Override <ide> public void write(Filer filer) throws IOException { <del> // check disk contents <del> if (source.equals(getResourceFileContents(filer, "", fileName))) { <add> // check disk contents before writing the generated file again to avoid causing needless rebuilds <add> if (checkResourceFileUpToDate(filer, fileName, source)) { <ide> return; <ide> } <ide> <ide> } <ide> <ide> /** <del> * Reads the contents of a generated resource file if it exists. <add> * Checks that a generated resource file exists on disk and the contents matches the expected string. <ide> * <del> * @param filer the Filer <del> * @param pkg package relative to which the file should be searched, or the empty string if none <del> * @param relativeName final pathname components of the file <add> * @param filer the Filer <add> * @param fileName the file name <ide> * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise <del> * @throws IOException if there is an I/O error during reading of file contents <ide> */ <del> private static String getResourceFileContents(Filer filer, String pkg, String relativeName) throws IOException { <del> InputStream is; <add> private static boolean checkResourceFileUpToDate(Filer filer, String fileName, String contents) { <ide> try { <del> is = filer.getResource(StandardLocation.CLASS_OUTPUT, pkg, relativeName).openInputStream(); <add> FileObject resourceFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", fileName); <add> try (InputStream is = resourceFile.openInputStream()) { <add> String existing = readUtf8String(is); <add> return contents.equals(existing); <add> } <ide> } catch (IOException e) { <del> return null; <del> } <del> <del> try { <del> return readUtf8String(is); <del> } finally { <del> is.close(); <add> return false; <ide> } <ide> } <ide> <ide> /** <del> * Reads the contents of a generated source file if it exists. <add> * Checks that a generated source file is up to date: it exists on disk, the contents matches the expected string and <add> * the corresponding class also exists and its timestamp is newer. <ide> * <ide> * @param filer the Filer <ide> * @param className fully qualified class name <add> * @param contents the expected contents of the source file <ide> * @return {@code true} if the file exists and contents is as expected, {@code false} otherwise <del> * @throws IOException if there is an I/O error during reading of file contents <ide> */ <del> private static String getSourceFileContents(Filer filer, String className) throws IOException { <del> InputStream is; <add> private static boolean checkSourceFileUpToDate(Filer filer, String className, String contents) { <add> String fileName = className.replace('.', '/'); <add> <add> long sourceTimestamp; <ide> try { <del> is = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", className.replace('.', '/') + ".java").openInputStream(); <add> FileObject javaFile = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", fileName + ".java"); <add> try (InputStream is = javaFile.openInputStream()) { <add> String existing = readUtf8String(is); <add> if (!contents.equals(existing)) { <add> return false; <add> } <add> } <add> sourceTimestamp = javaFile.getLastModified(); <ide> } catch (IOException e) { <del> return null; <del> } <del> <add> return false; <add> } <add> <add> long classTimestamp; <ide> try { <del> return readUtf8String(is); <del> } finally { <del> is.close(); <del> } <add> FileObject classFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", fileName + ".class"); <add> classTimestamp = classFile.getLastModified(); <add> } catch (IOException e) { <add> return false; <add> } <add> <add> return sourceTimestamp <= classTimestamp; <ide> } <ide> <ide> //todo [anistor] we assume that our source/resource files are all UTF-8
Java
mit
c433f096b4b43e9251d934898bf1003398ff2fd8
0
chicobentojr/minhaeiro
package br.com.chicobentojr.minhaeiro.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.Calendar; import br.com.chicobentojr.minhaeiro.R; import br.com.chicobentojr.minhaeiro.adapters.PeriodoPagerAdapter; import br.com.chicobentojr.minhaeiro.models.Movimentacao; import br.com.chicobentojr.minhaeiro.utils.P; public class PeriodoActivity extends AppCompatActivity { private PeriodoPagerAdapter pagerAdapter; private ViewPager viewPager; private TabLayout tabLayout; private ArrayList<Calendar> periodos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_periodo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.container); tabLayout = (TabLayout) findViewById(R.id.tabs); } @Override protected void onResume() { super.onResume(); carregarPeriodos(); abrirPeriodoMaisRecente(); } public void carregarPeriodos() { periodos = Movimentacao.obterPeriodos(P.getUsuarioInstance().Movimentacao); pagerAdapter = new PeriodoPagerAdapter(getSupportFragmentManager(), periodos, this); viewPager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(viewPager); } public void abrirPeriodoMaisRecente() { viewPager.setCurrentItem(periodos.size() - 1); } }
app/src/main/java/br/com/chicobentojr/minhaeiro/activity/PeriodoActivity.java
package br.com.chicobentojr.minhaeiro.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.Calendar; import br.com.chicobentojr.minhaeiro.R; import br.com.chicobentojr.minhaeiro.adapters.PeriodoPagerAdapter; import br.com.chicobentojr.minhaeiro.models.Movimentacao; import br.com.chicobentojr.minhaeiro.utils.P; public class PeriodoActivity extends AppCompatActivity { private PeriodoPagerAdapter pagerAdapter; private ViewPager viewPager; private TabLayout tabLayout; private ArrayList<Calendar> periodos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_periodo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.container); tabLayout = (TabLayout) findViewById(R.id.tabs); } @Override protected void onResume() { super.onResume(); carregarPeriodos(); } public void carregarPeriodos() { periodos = Movimentacao.obterPeriodos(P.getUsuarioInstance().Movimentacao); pagerAdapter = new PeriodoPagerAdapter(getSupportFragmentManager(), periodos, this); viewPager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(viewPager); } }
Adiciona função para abrir período mais recente
app/src/main/java/br/com/chicobentojr/minhaeiro/activity/PeriodoActivity.java
Adiciona função para abrir período mais recente
<ide><path>pp/src/main/java/br/com/chicobentojr/minhaeiro/activity/PeriodoActivity.java <ide> protected void onResume() { <ide> super.onResume(); <ide> carregarPeriodos(); <add> abrirPeriodoMaisRecente(); <ide> } <ide> <ide> public void carregarPeriodos() { <ide> viewPager.setAdapter(pagerAdapter); <ide> tabLayout.setupWithViewPager(viewPager); <ide> } <add> <add> public void abrirPeriodoMaisRecente() { <add> viewPager.setCurrentItem(periodos.size() - 1); <add> } <ide> }
Java
bsd-3-clause
91fb0f009fd7da91466aad71308962fca442b6a4
0
plan3/sns-to-orchestrate
package chids.providers; import static com.google.common.base.Strings.emptyToNull; import static java.lang.System.getenv; import io.orchestrate.client.Client; import java.lang.reflect.Type; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import chids.service.BadRequestException; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; @Provider public class ClientProvider extends AbstractHttpContextInjectable<Client> implements InjectableProvider<Context, Type> { public final static String APPLICATION = "application"; public final static String APPLICATIONp = '{' + APPLICATION + '}'; @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public Injectable<Client> getInjectable(final ComponentContext ic, final Context a, final Type c) { return c.equals(Client.class) ? this : null; } @Override public Client getValue(final HttpContext c) { final MultivaluedMap<String, String> parameters = c.getUriInfo().getPathParameters(true); final String application = assertNotNull(parameters.getFirst(APPLICATION), "No value for " + APPLICATION); final String apiKey = assertNotNull(getenv(application), application + " not configured"); return new Client(apiKey); } private static String assertNotNull(final String value, final String message) { if(emptyToNull(value) == null) { throw new BadRequestException(message); } return value; } }
src/main/java/chids/providers/ClientProvider.java
package chids.providers; import static com.google.common.base.Strings.emptyToNull; import static java.lang.System.getenv; import io.orchestrate.client.Client; import java.lang.reflect.Type; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import chids.service.BadRequestException; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; @Provider public class ClientProvider extends AbstractHttpContextInjectable<Client> implements InjectableProvider<Context, Type> { public final static String APPLICATION = "application"; public final static String APPLICATIONp = '{' + APPLICATION + '}'; @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public Injectable<Client> getInjectable(final ComponentContext ic, final Context a, final Type c) { return c.equals(Client.class) ? this : null; } @Override public Client getValue(final HttpContext c) { final String application = emptyToNull(c.getUriInfo().getPathParameters(true).getFirst(APPLICATION)); if(application == null) { throw new BadRequestException("No value for " + APPLICATION); } final String apiKey = emptyToNull(getenv(application)); if(apiKey == null) { throw new BadRequestException(application + " not configured"); } return new Client(apiKey); } }
Extract duplicated null checks to method in ClientProvider.
src/main/java/chids/providers/ClientProvider.java
Extract duplicated null checks to method in ClientProvider.
<ide><path>rc/main/java/chids/providers/ClientProvider.java <ide> import java.lang.reflect.Type; <ide> <ide> import javax.ws.rs.core.Context; <add>import javax.ws.rs.core.MultivaluedMap; <ide> import javax.ws.rs.ext.Provider; <ide> <ide> import chids.service.BadRequestException; <ide> <ide> @Override <ide> public Client getValue(final HttpContext c) { <del> final String application = emptyToNull(c.getUriInfo().getPathParameters(true).getFirst(APPLICATION)); <del> if(application == null) { <del> throw new BadRequestException("No value for " + APPLICATION); <del> } <del> final String apiKey = emptyToNull(getenv(application)); <del> if(apiKey == null) { <del> throw new BadRequestException(application + " not configured"); <del> } <add> final MultivaluedMap<String, String> parameters = c.getUriInfo().getPathParameters(true); <add> final String application = assertNotNull(parameters.getFirst(APPLICATION), "No value for " + APPLICATION); <add> final String apiKey = assertNotNull(getenv(application), application + " not configured"); <ide> return new Client(apiKey); <ide> } <add> <add> private static String assertNotNull(final String value, final String message) { <add> if(emptyToNull(value) == null) { <add> throw new BadRequestException(message); <add> } <add> return value; <add> } <ide> }
Java
apache-2.0
4409813025a0b44820599f6e3cf1011d31aa96a0
0
Valkryst/VTerminal
package com.valkryst.VTerminal.component; import com.valkryst.VTerminal.AsciiCharacter; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.AsciiString; import com.valkryst.VTerminal.font.Font; import com.valkryst.radio.Radio; import lombok.Getter; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class Component { /** The x-axis (column) coordinate of the top-left character. */ @Getter private int columnIndex; /** The y-axis (row) coordinate of the top-left character. */ @Getter private int rowIndex; /** The width, in characters. */ @Getter protected int width; /** The height, in characters. */ @Getter protected int height; /** Whether or not the component is currently the target of the user's input. */ @Getter private boolean isFocused = false; /** The bounding box. */ @Getter private Rectangle boundingBox = new Rectangle(); /** The strings representing the character-rows of the component. */ @Getter protected AsciiString[] strings; @Getter protected Radio<String> radio; /** * Constructs a new AsciiComponent. * * @param columnIndex * The x-axis (column) coordinate of the top-left character. * * @param rowIndex * The y-axis (row) coordinate of the top-left character. * * @param width * Thw width, in characters. * * @param height * The height, in characters. */ public Component(final int columnIndex, final int rowIndex, final int width, final int height) { if (columnIndex < 0) { throw new IllegalArgumentException("You must specify a columnIndex of 0 or greater."); } if (rowIndex < 0) { throw new IllegalArgumentException("You must specify a rowIndex of 0 or greater."); } if (width < 1) { throw new IllegalArgumentException("You must specify a width of 1 or greater."); } if (height < 1) { throw new IllegalArgumentException("You must specify a height of 1 or greater."); } this.columnIndex = columnIndex; this.rowIndex = rowIndex; this.width = width; this.height = height; boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(width, height); strings = new AsciiString[height]; for (int row = 0 ; row < height ; row++) { strings[row] = new AsciiString(width); } } /** * Registers events, required by the component, with the specified panel. * * @param panel * The panel to register events with. */ public void registerEventHandlers(final Panel panel) { final Font font = panel.getAsciiFont(); final int fontWidth = font.getWidth(); final int fontHeight = font.getHeight(); panel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { isFocused = intersects(e, fontWidth, fontHeight); } } @Override public void mousePressed(final MouseEvent e) {} @Override public void mouseReleased(final MouseEvent e) {} @Override public void mouseEntered(final MouseEvent e) {} @Override public void mouseExited(final MouseEvent e) {} }); } /** * Draws the component on the specified screen. * * @param screen * The screen to draw on. */ public void draw(final Screen screen) { for (int row = 0 ; row < strings.length ; row++) { screen.write(strings[row], columnIndex, rowIndex + row); } } /** Attempts to transmit a "DRAW" event to the assigned Radio. */ public void transmitDraw() { if (radio != null) { radio.transmit("DRAW"); } } /** * Determines if the specified component intersects with this component. * * @param otherComponent * The component to check intersection with. * * @return * Whether or not the components intersect. */ public boolean intersects(final Component otherComponent) { return otherComponent != null && boundingBox.intersects(otherComponent.getBoundingBox()); } /** * Determines if the specified point intersects with this component. * * @param pointX * The x-axis (column) coordinate. * * @param pointY * The y-axis (row) coordinate. * * @return * Whether or not the point intersects with this component. */ public boolean intersects(final int pointX, final int pointY) { boolean intersects = pointX >= columnIndex; intersects &= pointX < (boundingBox.getWidth() + columnIndex); intersects &= pointY >= rowIndex; intersects &= pointY < (boundingBox.getHeight() + rowIndex); return intersects; } /** * Determines whether or not the specified mouse event is at a point that intersects this component. * * @param event * The event. * * @param fontWidth * The width of the font being used to draw the component's characters. * * @param fontHeight * The height of the font being used to draw the component's characters. * * @return * Whether or not the mouse event is at a point that intersects this component. */ public boolean intersects(final MouseEvent event, final int fontWidth, final int fontHeight) { final int mouseX = event.getX() / fontWidth; final int mouseY = event.getY() / fontHeight; return intersects(mouseX, mouseY); } /** * Determines whether or not the specified position is within the bounds of the component. * * @param columnIndex * The x-axis (column) coordinate. * * @param rowIndex * The y-axis (row) coordinate. * * @return * Whether or not the specified position is within the bounds of the component. */ protected boolean isPositionValid(final int columnIndex, final int rowIndex) { if (rowIndex < 0 || rowIndex > boundingBox.getHeight()) { return false; } if (columnIndex < 0 || columnIndex > boundingBox.getWidth()) { return false; } return true; } /** * Enables the blink effect for every character. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.enableBlinkEffect(millsBetweenBlinks, radio); } } } /** Resumes the blink effect for every character. */ public void resumeBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.resumeBlinkEffect(); } } } /** Pauses the blink effect for every character. */ public void pauseBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.pauseBlinkEffect(); } } } /** Disables the blink effect for every character. */ public void disableBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.disableBlinkEffect(); } } } /** * Sets a new value for the columnIndex. * * Does nothing if the specified columnIndex is < 0. * * @param columnIndex * The new x-axis (column) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public boolean setColumnIndex(final int columnIndex) { if (columnIndex < 0) { return false; } this.columnIndex = columnIndex; boundingBox.setLocation(columnIndex, rowIndex); return true; } /** * Sets a new value for the rowIndex. * * Does nothing if the specified rowIndex is < 0. * * @param rowIndex * The y-axis (row) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public boolean setRowIndex(final int rowIndex) { if (rowIndex < 0) { return false; } this.rowIndex = rowIndex; boundingBox.setLocation(columnIndex, rowIndex); return true; } /** * Sets a new value for the width. * * Does nothing if the specified width is < 0 or < columnIndex. * * @param width * The new width, in characters, of the component. * * @return * Whether or not the new value was set. */ public boolean setWidth(final int width) { if (width < 0 || width < columnIndex) { return false; } this.width = width; boundingBox.setSize(width, height); return true; } /** * Sets a new value for the height. * * Does nothing if the specified height is < 0 or < rowIndex. * * @param height * The new height, in characters, of the component. * * @return * Whether or not the new value was set. */ public boolean setHeight(final int height) { if (height < 0 || height < rowIndex) { return false; } this.height = height; boundingBox.setSize(width, height); return true; } /** * Sets a new radio. * * @param radio * The new radio. */ public void setRadio(final Radio<String> radio) { if (radio != null) { this.radio = radio; } } }
src/com/valkryst/VTerminal/component/Component.java
package com.valkryst.VTerminal.component; import com.valkryst.VTerminal.AsciiCharacter; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.AsciiString; import com.valkryst.VTerminal.font.Font; import com.valkryst.radio.Radio; import lombok.Getter; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class Component { /** The x-axis (column) coordinate of the top-left character. */ @Getter private int columnIndex; /** The y-axis (row) coordinate of the top-left character. */ @Getter private int rowIndex; /** The width, in characters. */ @Getter protected int width; /** The height, in characters. */ @Getter protected int height; /** Whether or not the component is currently the target of the user's input. */ @Getter private boolean isFocused = false; /** The bounding box. */ @Getter private Rectangle boundingBox = new Rectangle(); /** The strings representing the character-rows of the component. */ @Getter protected AsciiString[] strings; @Getter protected Radio<String> radio; /** * Constructs a new AsciiComponent. * * @param columnIndex * The x-axis (column) coordinate of the top-left character. * * @param rowIndex * The y-axis (row) coordinate of the top-left character. * * @param width * Thw width, in characters. * * @param height * The height, in characters. */ public Component(final int columnIndex, final int rowIndex, final int width, final int height) { if (columnIndex < 0) { throw new IllegalArgumentException("You must specify a columnIndex of 0 or greater."); } if (rowIndex < 0) { throw new IllegalArgumentException("You must specify a rowIndex of 0 or greater."); } if (width < 1) { throw new IllegalArgumentException("You must specify a width of 1 or greater."); } if (height < 1) { throw new IllegalArgumentException("You must specify a height of 1 or greater."); } this.columnIndex = columnIndex; this.rowIndex = rowIndex; this.width = width; this.height = height; boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(width, height); strings = new AsciiString[height]; for (int row = 0 ; row < height ; row++) { strings[row] = new AsciiString(width); } } /** * Registers events, required by the component, with the specified panel. * * @param panel * The panel to register events with. */ public void registerEventHandlers(final Panel panel) { final Font font = panel.getAsciiFont(); final int fontWidth = font.getWidth(); final int fontHeight = font.getHeight(); panel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { isFocused = intersects(e, fontWidth, fontHeight); } } @Override public void mousePressed(final MouseEvent e) {} @Override public void mouseReleased(final MouseEvent e) {} @Override public void mouseEntered(final MouseEvent e) {} @Override public void mouseExited(final MouseEvent e) {} }); } /** * Draws the component on the specified screen. * * @param screen * The screen to draw on. */ public void draw(final Screen screen) { for (int row = 0 ; row < strings.length ; row++) { screen.write(strings[row], columnIndex, rowIndex + row); } } /** Attempts to transmit a "DRAW" event to the assigned Radio. */ public void transmitDraw() { if (radio != null) { radio.transmit("DRAW"); } } /** * Determines if the specified component intersects with this component. * * @param otherComponent * The component to check intersection with. * * @return * Whether or not the components intersect. */ public boolean intersects(final Component otherComponent) { return boundingBox.intersects(otherComponent.getBoundingBox()); } /** * Determines if the specified point intersects with this component. * * @param pointX * The x-axis (column) coordinate. * * @param pointY * The y-axis (row) coordinate. * * @return * Whether or not the point intersects with this component. */ public boolean intersects(final int pointX, final int pointY) { boolean intersects = pointX >= columnIndex; intersects &= pointX < (boundingBox.getWidth() + columnIndex); intersects &= pointY >= rowIndex; intersects &= pointY < (boundingBox.getHeight() + rowIndex); return intersects; } /** * Determines whether or not the specified mouse event is at a point that intersects this component. * * @param event * The event. * * @param fontWidth * The width of the font being used to draw the component's characters. * * @param fontHeight * The height of the font being used to draw the component's characters. * * @return * Whether or not the mouse event is at a point that intersects this component. */ public boolean intersects(final MouseEvent event, final int fontWidth, final int fontHeight) { final int mouseX = event.getX() / fontWidth; final int mouseY = event.getY() / fontHeight; return intersects(mouseX, mouseY); } /** * Determines whether or not the specified position is within the bounds of the component. * * @param columnIndex * The x-axis (column) coordinate. * * @param rowIndex * The y-axis (row) coordinate. * * @return * Whether or not the specified position is within the bounds of the component. */ protected boolean isPositionValid(final int columnIndex, final int rowIndex) { if (rowIndex < 0 || rowIndex > boundingBox.getHeight()) { return false; } if (columnIndex < 0 || columnIndex > boundingBox.getWidth()) { return false; } return true; } /** * Enables the blink effect for every character. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.enableBlinkEffect(millsBetweenBlinks, radio); } } } /** Resumes the blink effect for every character. */ public void resumeBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.resumeBlinkEffect(); } } } /** Pauses the blink effect for every character. */ public void pauseBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.pauseBlinkEffect(); } } } /** Disables the blink effect for every character. */ public void disableBlinkEffect() { for (final AsciiString s: strings) { for (final AsciiCharacter c : s.getCharacters()) { c.disableBlinkEffect(); } } } /** * Sets a new value for the columnIndex. * * Does nothing if the specified columnIndex is < 0. * * @param columnIndex * The new x-axis (column) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public boolean setColumnIndex(final int columnIndex) { if (columnIndex < 0) { return false; } this.columnIndex = columnIndex; boundingBox.setLocation(columnIndex, rowIndex); return true; } /** * Sets a new value for the rowIndex. * * Does nothing if the specified rowIndex is < 0. * * @param rowIndex * The y-axis (row) coordinate of the top-left character of the component. * * @return * Whether or not the new value was set. */ public boolean setRowIndex(final int rowIndex) { if (rowIndex < 0) { return false; } this.rowIndex = rowIndex; boundingBox.setLocation(columnIndex, rowIndex); return true; } /** * Sets a new value for the width. * * Does nothing if the specified width is < 0 or < columnIndex. * * @param width * The new width, in characters, of the component. * * @return * Whether or not the new value was set. */ public boolean setWidth(final int width) { if (width < 0 || width < columnIndex) { return false; } this.width = width; boundingBox.setSize(width, height); return true; } /** * Sets a new value for the height. * * Does nothing if the specified height is < 0 or < rowIndex. * * @param height * The new height, in characters, of the component. * * @return * Whether or not the new value was set. */ public boolean setHeight(final int height) { if (height < 0 || height < rowIndex) { return false; } this.height = height; boundingBox.setSize(width, height); return true; } /** * Sets a new radio. * * @param radio * The new radio. */ public void setRadio(final Radio<String> radio) { if (radio != null) { this.radio = radio; } } }
Adds null check to the intersects function.
src/com/valkryst/VTerminal/component/Component.java
Adds null check to the intersects function.
<ide><path>rc/com/valkryst/VTerminal/component/Component.java <ide> * Whether or not the components intersect. <ide> */ <ide> public boolean intersects(final Component otherComponent) { <del> return boundingBox.intersects(otherComponent.getBoundingBox()); <add> return otherComponent != null && boundingBox.intersects(otherComponent.getBoundingBox()); <add> <ide> } <ide> <ide> /**
Java
apache-2.0
38e9e0cb022fd60ba56cd8b6e223ceb6bd4de81a
0
darranl/directory-shared
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.shared.ldap.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.naming.InvalidNameException; import org.apache.directory.shared.asn1.codec.binary.Hex; import org.apache.directory.shared.i18n.I18n; import org.apache.directory.shared.ldap.entry.BinaryValue; import org.apache.directory.shared.ldap.entry.StringValue; import org.apache.directory.shared.ldap.schema.syntaxCheckers.UuidSyntaxChecker; /** * Various string manipulation methods that are more efficient then chaining * string operations: all is done in the same buffer without creating a bunch of * string objects. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ */ public class StringTools { /** The default charset, because it's not provided by JDK 1.5 */ static String defaultCharset = null; // ~ Static fields/initializers // ----------------------------------------------------------------- /** Hex chars */ private static final byte[] HEX_CHAR = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final int UTF8_MULTI_BYTES_MASK = 0x0080; private static final int UTF8_TWO_BYTES_MASK = 0x00E0; private static final int UTF8_TWO_BYTES = 0x00C0; private static final int UTF8_THREE_BYTES_MASK = 0x00F0; private static final int UTF8_THREE_BYTES = 0x00E0; private static final int UTF8_FOUR_BYTES_MASK = 0x00F8; private static final int UTF8_FOUR_BYTES = 0x00F0; private static final int UTF8_FIVE_BYTES_MASK = 0x00FC; private static final int UTF8_FIVE_BYTES = 0x00F8; private static final int UTF8_SIX_BYTES_MASK = 0x00FE; private static final int UTF8_SIX_BYTES = 0x00FC; /** &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] */ private static final boolean[] ALPHA = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha-lower-case> ::= [0x61-0x7A] */ private static final boolean[] ALPHA_LOWER_CASE = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha-upper-case> ::= [0x41-0x5A] */ private static final boolean[] ALPHA_UPPER_CASE = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; /** &lt;alpha-digit> | &lt;digit> */ private static final boolean[] ALPHA_DIGIT = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha> | &lt;digit> | '-' */ private static final boolean[] CHAR = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** %01-%27 %2B-%5B %5D-%7F */ private static final boolean[] UNICODE_SUBSET = { false, true, true, true, true, true, true, true, // '\0' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, // '(', ')', '*' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, // '\' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, }; /** '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' */ private static final boolean[] DIGIT = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */ private static final boolean[] HEX = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; /** A table containing booleans when the corresponding char is printable */ private static final boolean[] IS_PRINTABLE_CHAR = { false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- true, false, false, false, false, false, false, true, // ' ', ---, ---, ---, ---, ---, ---, "'" true, true, false, true, true, true, true, true, // '(', ')', ---, '+', ',', '-', '.', '/' true, true, true, true, true, true, true, true, // '0', '1', '2', '3', '4', '5', '6', '7', true, true, true, false, false, true, false, true, // '8', '9', ':', ---, ---, '=', ---, '?' false, true, true, true, true, true, true, true, // ---, 'A', 'B', 'C', 'D', 'E', 'F', 'G', true, true, true, true, true, true, true, true, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' true, true, true, true, true, true, true, true, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' true, true, true, false, false, false, false, false, // 'X', 'Y', 'Z', ---, ---, ---, ---, --- false, true, true, true, true, true, true, true, // ---, 'a', 'b', 'c', 'd', 'e', 'f', 'g' true, true, true, true, true, true, true, true, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' true, true, true, true, true, true, true, true, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' true, true, true, false, false, false, false, false // 'x', 'y', 'z', ---, ---, ---, ---, --- }; /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */ private static final byte[] HEX_VALUE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00 -> 0F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10 -> 1F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20 -> 2F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 30 -> 3F ( 0, 1,2, 3, 4,5, 6, 7, 8, 9 ) -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 40 -> 4F ( A, B, C, D, E, F ) -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 50 -> 5F -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 // 60 -> 6F ( a, b, c, d, e, f ) }; private static final char[] TO_LOWER_CASE = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, ' ', 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, '\'', '(', ')', 0x2A, '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', 0x3B, 0x3C, '=', 0x3E, '?', 0x40, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, }; /** upperCase = 'A' .. 'Z', '0'..'9', '-' */ private static final char[] UPPER_CASE = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '-', 0, 0, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 0, 0, 0, 0, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private static final int CHAR_ONE_BYTE_MASK = 0xFFFFFF80; private static final int CHAR_TWO_BYTES_MASK = 0xFFFFF800; private static final int CHAR_THREE_BYTES_MASK = 0xFFFF0000; private static final int CHAR_FOUR_BYTES_MASK = 0xFFE00000; private static final int CHAR_FIVE_BYTES_MASK = 0xFC000000; private static final int CHAR_SIX_BYTES_MASK = 0x80000000; public static final int NOT_EQUAL = -1; // The following methods are taken from org.apache.commons.lang.StringUtils /** * The empty String <code>""</code>. * * @since 2.0 */ public static final String EMPTY = ""; /** * The empty byte[] */ public static final byte[] EMPTY_BYTES = new byte[] {}; /** * The empty String[] */ public static final String[] EMPTY_STRINGS = new String[] {}; /** * Trims several consecutive characters into one. * * @param str * the string to trim consecutive characters of * @param ch * the character to trim down * @return the newly trimmed down string */ public static final String trimConsecutiveToOne( String str, char ch ) { if ( ( null == str ) || ( str.length() == 0 ) ) { return ""; } char[] buffer = str.toCharArray(); char[] newbuf = new char[buffer.length]; int pos = 0; boolean same = false; for ( int i = 0; i < buffer.length; i++ ) { char car = buffer[i]; if ( car == ch ) { if ( same ) { continue; } else { same = true; newbuf[pos++] = car; } } else { same = false; newbuf[pos++] = car; } } return new String( newbuf, 0, pos ); } /** * A deep trim of a string remove whitespace from the ends as well as * excessive whitespace within the inside of the string between * non-whitespace characters. A deep trim reduces internal whitespace down * to a single space to perserve the whitespace separated tokenization order * of the String. * * @param string the string to deep trim. * @return the trimmed string. */ public static final String deepTrim( String string ) { return deepTrim( string, false ); } /** * This does the same thing as a trim but we also lowercase the string while * performing the deep trim within the same buffer. This saves us from * having to create multiple String and StringBuffer objects and is much * more efficient. * * @see StringTools#deepTrim( String ) */ public static final String deepTrimToLower( String string ) { return deepTrim( string, true ); } /** * Put common code to deepTrim(String) and deepTrimToLower here. * * @param str the string to deep trim * @param toLowerCase how to normalize for case: upper or lower * @return the deep trimmed string * @see StringTools#deepTrim( String ) * * TODO Replace the toCharArray() by substring manipulations */ public static final String deepTrim( String str, boolean toLowerCase ) { if ( ( null == str ) || ( str.length() == 0 ) ) { return ""; } char ch; char[] buf = str.toCharArray(); char[] newbuf = new char[buf.length]; boolean wsSeen = false; boolean isStart = true; int pos = 0; for ( int i = 0; i < str.length(); i++ ) { ch = buf[i]; // filter out all uppercase characters if ( toLowerCase && Character.isUpperCase( ch ) ) { ch = Character.toLowerCase( ch ); } // Check to see if we should add space if ( Character.isWhitespace( ch ) ) { // If the buffer has had characters added already check last // added character. Only append a spc if last character was // not whitespace. if ( wsSeen ) { continue; } else { wsSeen = true; if ( isStart ) { isStart = false; } else { newbuf[pos++] = ch; } } } else { // Add all non-whitespace wsSeen = false; isStart = false; newbuf[pos++] = ch; } } return ( pos == 0 ? "" : new String( newbuf, 0, ( wsSeen ? pos - 1 : pos ) ) ); } /** * Truncates large Strings showing a portion of the String's head and tail * with the center cut out and replaced with '...'. Also displays the total * length of the truncated string so size of '...' can be interpreted. * Useful for large strings in UIs or hex dumps to log files. * * @param str the string to truncate * @param head the amount of the head to display * @param tail the amount of the tail to display * @return the center truncated string */ public static final String centerTrunc( String str, int head, int tail ) { StringBuffer buf = null; // Return as-is if String is smaller than or equal to the head plus the // tail plus the number of characters added to the trunc representation // plus the number of digits in the string length. if ( str.length() <= ( head + tail + 7 + str.length() / 10 ) ) { return str; } buf = new StringBuffer(); buf.append( '[' ).append( str.length() ).append( "][" ); buf.append( str.substring( 0, head ) ).append( "..." ); buf.append( str.substring( str.length() - tail ) ); buf.append( ']' ); return buf.toString(); } /** * Gets a hex string from byte array. * * @param res * the byte array * @return the hex string representing the binary values in the array */ public static final String toHexString( byte[] res ) { StringBuffer buf = new StringBuffer( res.length << 1 ); for ( int ii = 0; ii < res.length; ii++ ) { String digit = Integer.toHexString( 0xFF & res[ii] ); if ( digit.length() == 1 ) { digit = '0' + digit; } buf.append( digit ); } return buf.toString().toUpperCase(); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. * * @param value The String to lowercase * @return The lowercase string */ public static final String toLowerCase( String value ) { if ( ( null == value ) || ( value.length() == 0 ) ) { return ""; } char[] chars = value.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { chars[i] = TO_LOWER_CASE[ chars[i] ]; } return new String( chars ); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. * * @param value The String to uppercase * @return The uppercase string */ public static final String toUpperCase( String value ) { if ( ( null == value ) || ( value.length() == 0 ) ) { return ""; } char[] chars = value.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { chars[i] = UPPER_CASE[ chars[i] ]; } return new String( chars ); } /** * Get byte array from hex string * * @param hexString * the hex string to convert to a byte array * @return the byte form of the hex string. */ public static final byte[] toByteArray( String hexString ) { int arrLength = hexString.length() >> 1; byte buf[] = new byte[arrLength]; for ( int ii = 0; ii < arrLength; ii++ ) { int index = ii << 1; String l_digit = hexString.substring( index, index + 2 ); buf[ii] = ( byte ) Integer.parseInt( l_digit, 16 ); } return buf; } /** * This method is used to insert HTML block dynamically * * @param source the HTML code to be processes * @param replaceNl if true '\n' will be replaced by &lt;br> * @param replaceTag if true '<' will be replaced by &lt; and '>' will be replaced * by &gt; * @param replaceQuote if true '\"' will be replaced by &quot; * @return the formated html block */ public static final String formatHtml( String source, boolean replaceNl, boolean replaceTag, boolean replaceQuote ) { StringBuffer buf = new StringBuffer(); int len = source.length(); for ( int ii = 0; ii < len; ii++ ) { char ch = source.charAt( ii ); switch ( ch ) { case '\"': if ( replaceQuote ) { buf.append( "&quot;" ); } else { buf.append( ch ); } break; case '<': if ( replaceTag ) { buf.append( "&lt;" ); } else { buf.append( ch ); } break; case '>': if ( replaceTag ) { buf.append( "&gt;" ); } else { buf.append( ch ); } break; case '\n': if ( replaceNl ) { if ( replaceTag ) { buf.append( "&lt;br&gt;" ); } else { buf.append( "<br>" ); } } else { buf.append( ch ); } break; case '\r': break; case '&': buf.append( "&amp;" ); break; default: buf.append( ch ); break; } } return buf.toString(); } /** * Creates a regular expression from an LDAP substring assertion filter * specification. * * @param initialPattern * the initial fragment before wildcards * @param anyPattern * fragments surrounded by wildcards if any * @param finalPattern * the final fragment after last wildcard if any * @return the regular expression for the substring match filter * @throws PatternSyntaxException * if a syntactically correct regular expression cannot be * compiled */ public static final Pattern getRegex( String initialPattern, String[] anyPattern, String finalPattern ) throws PatternSyntaxException { StringBuffer buf = new StringBuffer(); if ( initialPattern != null ) { buf.append( '^' ).append( Pattern.quote( initialPattern ) ); } if ( anyPattern != null ) { for ( int i = 0; i < anyPattern.length; i++ ) { buf.append( ".*" ).append( Pattern.quote( anyPattern[i] ) ); } } if ( finalPattern != null ) { buf.append( ".*" ).append( Pattern.quote( finalPattern ) ); } else { buf.append( ".*" ); } return Pattern.compile( buf.toString() ); } /** * Generates a regular expression from an LDAP substring match expression by * parsing out the supplied string argument. * * @param ldapRegex * the substring match expression * @return the regular expression for the substring match filter * @throws PatternSyntaxException * if a syntactically correct regular expression cannot be * compiled */ public static final Pattern getRegex( String ldapRegex ) throws PatternSyntaxException { if ( ldapRegex == null ) { throw new PatternSyntaxException( I18n.err( I18n.ERR_04429 ), "null", -1 ); } List<String> any = new ArrayList<String>(); String remaining = ldapRegex; int index = remaining.indexOf( '*' ); if ( index == -1 ) { throw new PatternSyntaxException( I18n.err( I18n.ERR_04430 ), remaining, -1 ); } String initialPattern = null; if ( remaining.charAt( 0 ) != '*' ) { initialPattern = remaining.substring( 0, index ); } remaining = remaining.substring( index + 1, remaining.length() ); while ( ( index = remaining.indexOf( '*' ) ) != -1 ) { any.add( remaining.substring( 0, index ) ); remaining = remaining.substring( index + 1, remaining.length() ); } String finalPattern = null; if ( !remaining.endsWith( "*" ) && remaining.length() > 0 ) { finalPattern = remaining; } if ( any.size() > 0 ) { String[] anyStrs = new String[any.size()]; for ( int i = 0; i < anyStrs.length; i++ ) { anyStrs[i] = any.get( i ); } return getRegex( initialPattern, anyStrs, finalPattern ); } return getRegex( initialPattern, null, finalPattern ); } /** * Splits apart a OS separator delimited set of paths in a string into * multiple Strings. File component path strings are returned within a List * in the order they are found in the composite path string. Optionally, a * file filter can be used to filter out path strings to control the * components returned. If the filter is null all path components are * returned. * * @param paths * a set of paths delimited using the OS path separator * @param filter * a FileFilter used to filter the return set * @return the filter accepted path component Strings in the order * encountered */ @SuppressWarnings("PMD.CollapsibleIfStatements") // Used because of comments public static final List<String> getPaths( String paths, FileFilter filter ) { int start = 0; int stop = -1; String path = null; List<String> list = new ArrayList<String>(); // Abandon with no values if paths string is null if ( paths == null || paths.trim().equals( "" ) ) { return list; } final int max = paths.length() - 1; // Loop spliting string using OS path separator: terminate // when the start index is at the end of the paths string. while ( start < max ) { stop = paths.indexOf( File.pathSeparatorChar, start ); // The is no file sep between the start and the end of the string if ( stop == -1 ) { // If we have a trailing path remaining without ending separator if ( start < max ) { // Last path is everything from start to the string's end path = paths.substring( start ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the // path only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } } break; // Exit loop no more path components left! } // There is a separator between start and the end if we got here! // start index is now at 0 or the index of last separator + 1 // stop index is now at next separator in front of start index path = paths.substring( start, stop ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the path // only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } // Advance start index past separator to start of next path comp start = stop + 1; } return list; } // ~ Methods // ------------------------------------------------------------------------------------ /** * Helper function that dump a byte in hex form * * @param octet The byte to dump * @return A string representation of the byte */ public static final String dumpByte( byte octet ) { return new String( new byte[] { '0', 'x', HEX_CHAR[( octet & 0x00F0 ) >> 4], HEX_CHAR[octet & 0x000F] } ); } /** * Helper function that returns a char from an hex * * @param hex The hex to dump * @return A char representation of the hex */ public static final char dumpHex( byte hex ) { return ( char ) HEX_CHAR[hex & 0x000F]; } /** * Helper function that dump an array of bytes in hex form * * @param buffer The bytes array to dump * @return A string representation of the array of bytes */ public static final String dumpBytes( byte[] buffer ) { if ( buffer == null ) { return ""; } StringBuffer sb = new StringBuffer(); for ( int i = 0; i < buffer.length; i++ ) { sb.append( "0x" ).append( ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ) ).append( ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ) ).append( " " ); } return sb.toString(); } /** * * Helper method to render an object which can be a String or a byte[] * * @return A string representing the object */ public static String dumpObject( Object object ) { if ( object != null ) { if ( object instanceof String ) { return (String) object; } else if ( object instanceof byte[] ) { return dumpBytes( ( byte[] ) object ); } else if ( object instanceof StringValue ) { return ( ( StringValue ) object ).get(); } else if ( object instanceof BinaryValue ) { return dumpBytes( ( ( BinaryValue ) object ).get() ); } else { return "<unknown type>"; } } else { return ""; } } /** * Helper function that dump an array of bytes in hex pair form, * without '0x' and space chars * * @param buffer The bytes array to dump * @return A string representation of the array of bytes */ public static final String dumpHexPairs( byte[] buffer ) { if ( buffer == null ) { return ""; } char[] str = new char[buffer.length << 1]; for ( int i = 0, pos = 0; i < buffer.length; i++ ) { str[pos++] = ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ); str[pos++] = ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ); } return new String( str ); } /** * Return the Unicode char which is coded in the bytes at position 0. * * @param bytes The byte[] represntation of an Unicode string. * @return The first char found. */ public static final char bytesToChar( byte[] bytes ) { return bytesToChar( bytes, 0 ); } /** * Count the number of bytes needed to return an Unicode char. This can be * from 1 to 6. * * @param bytes The bytes to read * @param pos Position to start counting. It must be a valid start of a * encoded char ! * @return The number of bytes to create a char, or -1 if the encoding is * wrong. TODO : Should stop after the third byte, as a char is only * 2 bytes long. */ public static final int countBytesPerChar( byte[] bytes, int pos ) { if ( bytes == null ) { return -1; } if ( ( bytes[pos] & UTF8_MULTI_BYTES_MASK ) == 0 ) { return 1; } else if ( ( bytes[pos] & UTF8_TWO_BYTES_MASK ) == UTF8_TWO_BYTES ) { return 2; } else if ( ( bytes[pos] & UTF8_THREE_BYTES_MASK ) == UTF8_THREE_BYTES ) { return 3; } else if ( ( bytes[pos] & UTF8_FOUR_BYTES_MASK ) == UTF8_FOUR_BYTES ) { return 4; } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { return 5; } else if ( ( bytes[pos] & UTF8_SIX_BYTES_MASK ) == UTF8_SIX_BYTES ) { return 6; } else { return -1; } } /** * Return the number of bytes that hold an Unicode char. * * @param car The character to be decoded * @return The number of bytes to hold the char. TODO : Should stop after * the third byte, as a char is only 2 bytes long. */ public static final int countNbBytesPerChar( char car ) { if ( ( car & CHAR_ONE_BYTE_MASK ) == 0 ) { return 1; } else if ( ( car & CHAR_TWO_BYTES_MASK ) == 0 ) { return 2; } else if ( ( car & CHAR_THREE_BYTES_MASK ) == 0 ) { return 3; } else if ( ( car & CHAR_FOUR_BYTES_MASK ) == 0 ) { return 4; } else if ( ( car & CHAR_FIVE_BYTES_MASK ) == 0 ) { return 5; } else if ( ( car & CHAR_SIX_BYTES_MASK ) == 0 ) { return 6; } else { return -1; } } /** * Count the number of bytes included in the given char[]. * * @param chars The char array to decode * @return The number of bytes in the char array */ public static final int countBytes( char[] chars ) { if ( chars == null ) { return 0; } int nbBytes = 0; int currentPos = 0; while ( currentPos < chars.length ) { int nbb = countNbBytesPerChar( chars[currentPos] ); // If the number of bytes necessary to encode a character is // above 3, we will need two UTF-16 chars currentPos += ( nbb < 4 ? 1 : 2 ); nbBytes += nbb; } return nbBytes; } /** * Return the Unicode char which is coded in the bytes at the given * position. * * @param bytes The byte[] represntation of an Unicode string. * @param pos The current position to start decoding the char * @return The decoded char, or -1 if no char can be decoded TODO : Should * stop after the third byte, as a char is only 2 bytes long. */ public static final char bytesToChar( byte[] bytes, int pos ) { if ( bytes == null ) { return ( char ) -1; } if ( ( bytes[pos] & UTF8_MULTI_BYTES_MASK ) == 0 ) { return ( char ) bytes[pos]; } else { if ( ( bytes[pos] & UTF8_TWO_BYTES_MASK ) == UTF8_TWO_BYTES ) { // Two bytes char return ( char ) ( ( ( bytes[pos] & 0x1C ) << 6 ) + // 110x-xxyy // 10zz-zzzz // -> // 0000-0xxx // 0000-0000 ( ( bytes[pos] & 0x03 ) << 6 ) + // 110x-xxyy 10zz-zzzz // -> 0000-0000 // yy00-0000 ( bytes[pos + 1] & 0x3F ) // 110x-xxyy 10zz-zzzz -> 0000-0000 // 00zz-zzzz ); // -> 0000-0xxx yyzz-zzzz (07FF) } else if ( ( bytes[pos] & UTF8_THREE_BYTES_MASK ) == UTF8_THREE_BYTES ) { // Three bytes char return ( char ) ( // 1110-tttt 10xx-xxyy 10zz-zzzz -> tttt-0000-0000-0000 ( ( bytes[pos] & 0x0F ) << 12 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-xxxx-0000-0000 ( ( bytes[pos + 1] & 0x3C ) << 6 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-0000-yy00-0000 ( ( bytes[pos + 1] & 0x03 ) << 6 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-0000-00zz-zzzz ( bytes[pos + 2] & 0x3F ) // -> tttt-xxxx yyzz-zzzz (FF FF) ); } else if ( ( bytes[pos] & UTF8_FOUR_BYTES_MASK ) == UTF8_FOUR_BYTES ) { // Four bytes char return ( char ) ( // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 000t-tt00 // 0000-0000 0000-0000 ( ( bytes[pos] & 0x07 ) << 18 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-00uu // 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x30 ) << 16 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // vvvv-0000 0000-0000 ( ( bytes[pos + 1] & 0x0F ) << 12 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-xxxx 0000-0000 ( ( bytes[pos + 2] & 0x3C ) << 6 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-0000 yy00-0000 ( ( bytes[pos + 2] & 0x03 ) << 6 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-0000 00zz-zzzz ( bytes[pos + 3] & 0x3F ) // -> 000t-ttuu vvvv-xxxx yyzz-zzzz (1FFFFF) ); } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { // Five bytes char return ( char ) ( // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-00tt 0000-0000 0000-0000 0000-0000 ( ( bytes[pos] & 0x03 ) << 24 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 uuuu-uu00 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x3F ) << 18 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-00vv 0000-0000 0000-0000 ( ( bytes[pos + 2] & 0x30 ) << 12 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 wwww-0000 0000-0000 ( ( bytes[pos + 2] & 0x0F ) << 12 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-xxxx 0000-0000 ( ( bytes[pos + 3] & 0x3C ) << 6 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 yy00-0000 ( ( bytes[pos + 3] & 0x03 ) << 6 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 00zz-zzzz ( bytes[pos + 4] & 0x3F ) // -> 0000-00tt uuuu-uuvv wwww-xxxx yyzz-zzzz (03 FF FF FF) ); } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { // Six bytes char return ( char ) ( // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 0s00-0000 0000-0000 0000-0000 0000-0000 ( ( bytes[pos] & 0x01 ) << 30 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 00tt-tttt 0000-0000 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x3F ) << 24 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 uuuu-uu00 0000-0000 0000-0000 ( ( bytes[pos + 2] & 0x3F ) << 18 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-00vv 0000-0000 0000-0000 ( ( bytes[pos + 3] & 0x30 ) << 12 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 wwww-0000 0000-0000 ( ( bytes[pos + 3] & 0x0F ) << 12 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 0000-xxxx 0000-0000 ( ( bytes[pos + 4] & 0x3C ) << 6 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 yy00-0000 ( ( bytes[pos + 4] & 0x03 ) << 6 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 0000-0000 0000-0000 0000-0000 00zz-zzzz ( bytes[pos + 5] & 0x3F ) // -> 0stt-tttt uuuu-uuvv wwww-xxxx yyzz-zzzz (7F FF FF FF) ); } else { return ( char ) -1; } } } /** * Return the Unicode char which is coded in the bytes at the given * position. * * @param car The character to be transformed to an array of bytes * * @return The byte array representing the char * * TODO : Should stop after the third byte, as a char is only 2 bytes long. */ public static final byte[] charToBytes( char car ) { byte[] bytes = new byte[countNbBytesPerChar( car )]; if ( car <= 0x7F ) { // Single byte char bytes[0] = ( byte ) car; return bytes; } else if ( car <= 0x7FF ) { // two bytes char bytes[0] = ( byte ) ( 0x00C0 + ( ( car & 0x07C0 ) >> 6 ) ); bytes[1] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); } else { // Three bytes char bytes[0] = ( byte ) ( 0x00E0 + ( ( car & 0xF000 ) >> 12 ) ); bytes[1] = ( byte ) ( 0x0080 + ( ( car & 0x0FC0 ) >> 6 ) ); bytes[2] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); } return bytes; } /** * Count the number of chars included in the given byte[]. * * @param bytes The byte array to decode * @return The number of char in the byte array */ public static final int countChars( byte[] bytes ) { if ( bytes == null ) { return 0; } int nbChars = 0; int currentPos = 0; while ( currentPos < bytes.length ) { currentPos += countBytesPerChar( bytes, currentPos ); nbChars++; } return nbChars; } /** * Check if a text is present at the current position in a buffer. * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @param text The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( byte[] bytes, int index, String text ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( bytes.length <= index ) || ( index < 0 ) || ( text == null ) ) { return NOT_EQUAL; } else { try { byte[] data = text.getBytes( "UTF-8" ); return areEquals( bytes, index, data ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } } /** * Check if a text is present at the current position in a buffer. * * @param chars The buffer which contains the data * @param index Current position in the buffer * @param text The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( char[] chars, int index, String text ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( chars.length <= index ) || ( index < 0 ) || ( text == null ) ) { return NOT_EQUAL; } else { char[] data = text.toCharArray(); return areEquals( chars, index, data ); } } /** * Check if a text is present at the current position in a buffer. * * @param chars The buffer which contains the data * @param index Current position in the buffer * @param chars2 The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( char[] chars, int index, char[] chars2 ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( chars.length <= index ) || ( index < 0 ) || ( chars2 == null ) || ( chars2.length == 0 ) || ( chars2.length > ( chars.length + index ) ) ) { return NOT_EQUAL; } else { for ( int i = 0; i < chars2.length; i++ ) { if ( chars[index++] != chars2[i] ) { return NOT_EQUAL; } } return index; } } /** * Check if a text is present at the current position in another string. * * @param string The string which contains the data * @param index Current position in the string * @param text The text we want to check * @return <code>true</code> if the string contains the text. */ public static final boolean areEquals( String string, int index, String text ) { if ( ( string == null ) || ( text == null ) ) { return false; } int length1 = string.length(); int length2 = text.length(); if ( ( length1 == 0 ) || ( length1 <= index ) || ( index < 0 ) || ( length2 == 0 ) || ( length2 > ( length1 + index ) ) ) { return false; } else { return string.substring( index ).startsWith( text ); } } /** * Check if a text is present at the current position in a buffer. * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @param bytes2 The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( byte[] bytes, int index, byte[] bytes2 ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( bytes.length <= index ) || ( index < 0 ) || ( bytes2 == null ) || ( bytes2.length == 0 ) || ( bytes2.length > ( bytes.length + index ) ) ) { return NOT_EQUAL; } else { for ( int i = 0; i < bytes2.length; i++ ) { if ( bytes[index++] != bytes2[i] ) { return NOT_EQUAL; } } return index; } } /** * Test if the current character is equal to a specific character. This * function works only for character between 0 and 127, as it does compare a * byte and a char (which is 16 bits wide) * * @param byteArray * The buffer which contains the data * @param index * Current position in the buffer * @param car * The character we want to compare with the current buffer * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( byte[] byteArray, int index, char car ) { if ( ( byteArray == null ) || ( byteArray.length == 0 ) || ( index < 0 ) || ( index >= byteArray.length ) ) { return false; } else { return ( ( byteArray[index] == car ) ? true : false ); } } /** * Test if the current character is equal to a specific character. * * @param chars * The buffer which contains the data * @param index * Current position in the buffer * @param car * The character we want to compare with the current buffer * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( char[] chars, int index, char car ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { return ( ( chars[index] == car ) ? true : false ); } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( String string, int index, char car ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return string.charAt( index ) == car; } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isICharASCII( String string, int index, char car ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return ( ( string.charAt( index ) | 0x20 ) & car ) == car; } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isICharASCII( byte[] bytes, int index, char car ) { if ( bytes == null ) { return false; } int length = bytes.length; if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return ( ( bytes[ index ] | 0x20 ) & car ) == car; } } /** * Test if the current character is a bit, ie 0 or 1. * * @param string * The String which contains the data * @param index * Current position in the string * @return <code>true</code> if the current character is a bit (0 or 1) */ public static final boolean isBit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); return ( ( c == '0' ) || ( c == '1' ) ); } } /** * Get the character at a given position in a string, checking fo limits * * @param string The string which contains the data * @param index Current position in the string * @return The character ar the given position, or '\0' if something went wrong */ public static final char charAt( String string, int index ) { if ( string == null ) { return '\0'; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return '\0'; } else { return string.charAt( index ) ; } } /** * Translate two chars to an hex value. The chars must be * in [a-fA-F0-9] * * @param high The high value * @param low The low value * @return A byte representation of the two chars */ public static byte getHexValue( char high, char low ) { if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) ) { return -1; } return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] ); } /** * Translate two bytes to an hex value. The bytes must be * in [0-9a-fA-F] * * @param high The high value * @param low The low value * @return A byte representation of the two bytes */ public static byte getHexValue( byte high, byte low ) { if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) ) { return -1; } return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] ); } /** * Return an hex value from a sinle char * The char must be in [0-9a-fA-F] * * @param c The char we want to convert * @return A byte between 0 and 15 */ public static byte getHexValue( char c ) { if ( ( c > 127 ) || ( c < 0 ) ) { return -1; } return HEX_VALUE[c]; } /** * Check if the current byte is an Hex Char * &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] * * @param byte The byte we want to check * @return <code>true</code> if the current byte is a Hex byte */ public static final boolean isHex( byte b ) { return ( ( b | 0x7F ) == 0x7F ) || HEX[b]; } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param bytes The buffer which contains the data * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( byte[] bytes ) { if ( ( bytes == null ) || ( bytes.length == 0 ) ) { return false; } else { return ( ( ( ( bytes[0] | 0x7F ) != 0x7F ) || !DIGIT[bytes[0]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param car the character to test * * @return <code>true</code> if the character is a Digit */ public static final boolean isDigit( char car ) { return ( car >= '0' ) && ( car <= '9' ); } /** * Test if the current byte is an Alpha character : * &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] * * @param c The byte to test * * @return <code>true</code> if the byte is an Alpha * character */ public static final boolean isAlpha( byte c ) { return ( ( c > 0 ) && ( c <= 127 ) && ALPHA[c] ); } /** * Test if the current character is an Alpha character : * &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] * * @param c The char to test * * @return <code>true</code> if the character is an Alpha * character */ public static final boolean isAlpha( char c ) { return ( ( c > 0 ) && ( c <= 127 ) && ALPHA[c] ); } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a lowercased Alpha character : <br/> * &lt;alpha> ::= [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a lower Alpha * character */ public static final boolean isAlphaLowercaseASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_LOWER_CASE[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a uppercased Alpha character : <br/> * &lt;alpha> ::= [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a lower Alpha * character */ public static final boolean isAlphaUppercaseASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_UPPER_CASE[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { return ( ( ( ( bytes[index] | 0x7F ) != 0x7F ) || !DIGIT[bytes[index]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { return ( ( ( chars[index] > 127 ) || !DIGIT[chars[index]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); return ( ( ( c > 127 ) || !DIGIT[c] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param chars The buffer which contains the data * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( char[] chars ) { if ( ( chars == null ) || ( chars.length == 0 ) ) { return false; } else { return ( ( ( chars[0] > 127 ) || !DIGIT[chars[0]] ) ? false : true ); } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). * &lt;char> ::= &lt;alpha> | &lt;digit> * * @param string The string which contains the data * @param index Current position in the string * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_DIGIT[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param string The string which contains the data * @param index Current position in the string * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } // Empty checks // ----------------------------------------------------------------------- /** * <p> * Checks if a String is empty ("") or null. * </p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty(&quot;&quot;) = true * StringUtils.isEmpty(&quot; &quot;) = false * StringUtils.isEmpty(&quot;bob&quot;) = false * StringUtils.isEmpty(&quot; bob &quot;) = false * </pre> * * <p> * NOTE: This method changed in Lang version 2.0. It no longer trims the * String. That functionality is available in isBlank(). * </p> * * @param str the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static final boolean isEmpty( String str ) { return str == null || str.length() == 0; } /** * Checks if a bytes array is empty or null. * * @param bytes The bytes array to check, may be null * @return <code>true</code> if the bytes array is empty or null */ public static final boolean isEmpty( byte[] bytes ) { return bytes == null || bytes.length == 0; } /** * <p> * Checks if a String is not empty ("") and not null. * </p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty(&quot;&quot;) = false * StringUtils.isNotEmpty(&quot; &quot;) = true * StringUtils.isNotEmpty(&quot;bob&quot;) = true * StringUtils.isNotEmpty(&quot; bob &quot;) = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is not empty and not null */ public static final boolean isNotEmpty( String str ) { return str != null && str.length() > 0; } /** * <p> * Removes spaces (char &lt;= 32) from both start and ends of this String, * handling <code>null</code> by returning <code>null</code>. * </p> * Trim removes start and end characters &lt;= 32. * * <pre> * StringUtils.trim(null) = null * StringUtils.trim(&quot;&quot;) = &quot;&quot; * StringUtils.trim(&quot; &quot;) = &quot;&quot; * StringUtils.trim(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trim(&quot; abc &quot;) = &quot;abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trim( String str ) { return ( isEmpty( str ) ? "" : str.trim() ); } /** * <p> * Removes spaces (char &lt;= 32) from both start and ends of this bytes * array, handling <code>null</code> by returning <code>null</code>. * </p> * Trim removes start and end characters &lt;= 32. * * <pre> * StringUtils.trim(null) = null * StringUtils.trim(&quot;&quot;) = &quot;&quot; * StringUtils.trim(&quot; &quot;) = &quot;&quot; * StringUtils.trim(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trim(&quot; abc &quot;) = &quot;abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * * @return the trimmed byte array */ public static final byte[] trim( byte[] bytes ) { if ( isEmpty( bytes ) ) { return EMPTY_BYTES; } int start = trimLeft( bytes, 0 ); int end = trimRight( bytes, bytes.length - 1 ); int length = end - start + 1; if ( length != 0 ) { byte[] newBytes = new byte[end - start + 1]; System.arraycopy( bytes, start, newBytes, 0, length ); return newBytes; } else { return EMPTY_BYTES; } } /** * <p> * Removes spaces (char &lt;= 32) from start of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trimLeft( String str ) { if ( isEmpty( str ) ) { return ""; } int start = 0; int end = str.length(); while ( ( start < end ) && ( str.charAt( start ) == ' ' ) ) { start++; } return ( start == 0 ? str : str.substring( start ) ); } /** * <p> * Removes spaces (char &lt;= 32) from start of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param chars the chars array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimLeft( char[] chars, int pos ) { if ( chars == null ) { return pos; } while ( ( pos < chars.length ) && ( chars[pos] == ' ' ) ) { pos++; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from a position in this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;,...) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;,...) = &quot;abc &quot; * </pre> * * @param string the string to be trimmed, may be null * @param pos The starting position */ public static final void trimLeft( String string, Position pos ) { if ( string == null ) { return; } int length = string.length(); while ( ( pos.start < length ) && ( string.charAt( pos.start ) == ' ' ) ) { pos.start++; } pos.end = pos.start; } /** * <p> * Removes spaces (char &lt;= 32) from a position in this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;,...) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;,...) = &quot;abc &quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @param pos The starting position */ public static final void trimLeft( byte[] bytes, Position pos ) { if ( bytes == null ) { return; } int length = bytes.length; while ( ( pos.start < length ) && ( bytes[ pos.start ] == ' ' ) ) { pos.start++; } pos.end = pos.start; } /** * <p> * Removes spaces (char &lt;= 32) from start of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first byte which is not a space, or the last * position of the array. */ public static final int trimLeft( byte[] bytes, int pos ) { if ( bytes == null ) { return pos; } while ( ( pos < bytes.length ) && ( bytes[pos] == ' ' ) ) { pos++; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from end of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trimRight( String str ) { if ( isEmpty( str ) ) { return ""; } int length = str.length(); int end = length; while ( ( end > 0 ) && ( str.charAt( end - 1 ) == ' ' ) ) { if ( ( end > 1 ) && ( str.charAt( end - 2 ) == '\\' ) ) { break; } end--; } return ( end == length ? str : str.substring( 0, end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @param escapedSpace The last escaped space, if any * @return the trimmed string, <code>null</code> if null String input */ public static final String trimRight( String str, int escapedSpace ) { if ( isEmpty( str ) ) { return ""; } int length = str.length(); int end = length; while ( ( end > 0 ) && ( str.charAt( end - 1 ) == ' ' ) && ( end > escapedSpace ) ) { if ( ( end > 1 ) && ( str.charAt( end - 2 ) == '\\' ) ) { break; } end--; } return ( end == length ? str : str.substring( 0, end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param chars the chars array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimRight( char[] chars, int pos ) { if ( chars == null ) { return pos; } while ( ( pos >= 0 ) && ( chars[pos - 1] == ' ' ) ) { pos--; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from end of this string, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param string the string to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the string. */ public static final String trimRight( String string, Position pos ) { if ( string == null ) { return ""; } while ( ( pos.end >= 0 ) && ( string.charAt( pos.end - 1 ) == ' ' ) ) { if ( ( pos.end > 1 ) && ( string.charAt( pos.end - 2 ) == '\\' ) ) { break; } pos.end--; } return ( pos.end == string.length() ? string : string.substring( 0, pos.end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this string, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the byte array. */ public static final String trimRight( byte[] bytes, Position pos ) { if ( bytes == null ) { return ""; } while ( ( pos.end >= 0 ) && ( bytes[pos.end - 1] == ' ' ) ) { if ( ( pos.end > 1 ) && ( bytes[pos.end - 2] == '\\' ) ) { break; } pos.end--; } if ( pos.end == bytes.length ) { return StringTools.utf8ToString( bytes ); } else { return StringTools.utf8ToString( bytes, pos.end ); } } /** * <p> * Removes spaces (char &lt;= 32) from end of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimRight( byte[] bytes, int pos ) { if ( bytes == null ) { return pos; } while ( ( pos >= 0 ) && ( bytes[pos] == ' ' ) ) { pos--; } return pos; } // Case conversion // ----------------------------------------------------------------------- /** * <p> * Converts a String to upper case as per {@link String#toUpperCase()}. * </p> * <p> * A <code>null</code> input String returns <code>null</code>. * </p> * * <pre> * StringUtils.upperCase(null) = null * StringUtils.upperCase(&quot;&quot;) = &quot;&quot; * StringUtils.upperCase(&quot;aBc&quot;) = &quot;ABC&quot; * </pre> * * @param str the String to upper case, may be null * @return the upper cased String, <code>null</code> if null String input */ public static final String upperCase( String str ) { if ( str == null ) { return null; } return str.toUpperCase(); } /** * <p> * Converts a String to lower case as per {@link String#toLowerCase()}. * </p> * <p> * A <code>null</code> input String returns <code>null</code>. * </p> * * <pre> * StringUtils.lowerCase(null) = null * StringUtils.lowerCase(&quot;&quot;) = &quot;&quot; * StringUtils.lowerCase(&quot;aBc&quot;) = &quot;abc&quot; * </pre> * * @param str the String to lower case, may be null * @return the lower cased String, <code>null</code> if null String input */ public static final String lowerCase( String str ) { if ( str == null ) { return null; } return str.toLowerCase(); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. We will take * care of any other chars either. * * @param str The String to lowercase * @return The lowercase string */ public static final String lowerCaseAscii( String str ) { if ( str == null ) { return null; } char[] chars = str.toCharArray(); int pos = 0; for ( char c:chars ) { chars[pos++] = TO_LOWER_CASE[c]; } return new String( chars ); } // Equals // ----------------------------------------------------------------------- /** * <p> * Compares two Strings, returning <code>true</code> if they are equal. * </p> * <p> * <code>null</code>s are handled without exceptions. Two * <code>null</code> references are considered to be equal. The comparison * is case sensitive. * </p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, &quot;abc&quot;) = false * StringUtils.equals(&quot;abc&quot;, null) = false * StringUtils.equals(&quot;abc&quot;, &quot;abc&quot;) = true * StringUtils.equals(&quot;abc&quot;, &quot;ABC&quot;) = false * </pre> * * @see java.lang.String#equals(Object) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static final boolean equals( String str1, String str2 ) { return str1 == null ? str2 == null : str1.equals( str2 ); } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @return A String. */ public static final String utf8ToString( byte[] bytes ) { if ( bytes == null ) { return ""; } try { return new String( bytes, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @param length The length of the byte array to be converted * @return A String. */ public static final String utf8ToString( byte[] bytes, int length ) { if ( bytes == null ) { return ""; } try { return new String( bytes, 0, length, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @param start the starting position in the byte array * @param length The length of the byte array to be converted * @return A String. */ public static final String utf8ToString( byte[] bytes, int start, int length ) { if ( bytes == null ) { return ""; } try { return new String( bytes, start, length, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return UTF-8 encoded byte[] representation of a String * * @param string The string to be transformed to a byte array * @return The transformed byte array */ public static final byte[] getBytesUtf8( String string ) { if ( string == null ) { return new byte[0]; } try { return string.getBytes( "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Utility method that return a String representation of a list * * @param list The list to transform to a string * @return A csv string */ public static final String listToString( List<?> list ) { if ( ( list == null ) || ( list.size() == 0 ) ) { return ""; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object elem : list ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( elem ); } return sb.toString(); } /** * Utility method that return a String representation of a set * * @param set The set to transform to a string * @return A csv string */ public static final String setToString( Set<?> set ) { if ( ( set == null ) || ( set.size() == 0 ) ) { return ""; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object elem : set ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( elem ); } return sb.toString(); } /** * Utility method that return a String representation of a list * * @param list The list to transform to a string * @param tabs The tabs to add in ffront of the elements * @return A csv string */ public static final String listToString( List<?> list, String tabs ) { if ( ( list == null ) || ( list.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); for ( Object elem : list ) { sb.append( tabs ); sb.append( elem ); sb.append( '\n' ); } return sb.toString(); } /** * Utility method that return a String representation of a map. The elements * will be represented as "key = value" * * @param map The map to transform to a string * @return A csv string */ public static final String mapToString( Map<?,?> map ) { if ( ( map == null ) || ( map.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); boolean isFirst = true; for ( Map.Entry<?, ?> entry:map.entrySet() ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( entry.getKey() ); sb.append( " = '" ).append( entry.getValue() ).append( "'" ); } return sb.toString(); } /** * Utility method that return a String representation of a map. The elements * will be represented as "key = value" * * @param map The map to transform to a string * @param tabs The tabs to add in ffront of the elements * @return A csv string */ public static final String mapToString( Map<?,?> map, String tabs ) { if ( ( map == null ) || ( map.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); for ( Map.Entry<?, ?> entry:map.entrySet() ) { sb.append( tabs ); sb.append( entry.getKey() ); sb.append( " = '" ).append( entry.getValue().toString() ).append( "'\n" ); } return sb.toString(); } /** * Get the default charset * * @return The default charset */ public static final String getDefaultCharsetName() { if ( null == defaultCharset ) { try { // Try with jdk 1.5 method, if we are using a 1.5 jdk :) Method method = Charset.class.getMethod( "defaultCharset", new Class[0] ); defaultCharset = ((Charset) method.invoke( null, new Object[0]) ).name(); } catch (NoSuchMethodException e) { // fall back to old method defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); } catch (InvocationTargetException e) { // fall back to old method defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); } catch (IllegalAccessException e) { // fall back to old method defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); } } return defaultCharset; } /** * Decodes values of attributes in the DN encoded in hex into a UTF-8 * String. RFC2253 allows a DN's attribute to be encoded in hex. * The encoded value starts with a # then is followed by an even * number of hex characters. * * @param str the string to decode * @return the decoded string */ public static final String decodeHexString( String str ) throws InvalidNameException { if ( str == null || str.length() == 0 ) { throw new InvalidNameException( I18n.err( I18n.ERR_04431 ) ); } char[] chars = str.toCharArray(); if ( chars[0] != '#' ) { throw new InvalidNameException( I18n.err( I18n.ERR_04432, str ) ); } // the bytes representing the encoded string of hex // this should be ( length - 1 )/2 in size byte[] decoded = new byte[ ( chars.length - 1 ) >> 1 ]; for ( int ii = 1, jj = 0 ; ii < chars.length; ii+=2, jj++ ) { int ch = ( StringTools.HEX_VALUE[chars[ii]] << 4 ) + StringTools.HEX_VALUE[chars[ii+1]]; decoded[jj] = ( byte ) ch; } return StringTools.utf8ToString( decoded ); } /** * Convert an escaoed list of bytes to a byte[] * * @param str the string containing hex escapes * @return the converted byte[] */ public static final byte[] convertEscapedHex( String str ) throws InvalidNameException { if ( str == null ) { throw new InvalidNameException( I18n.err( I18n.ERR_04433 ) ); } int length = str.length(); if ( length == 0 ) { throw new InvalidNameException( I18n.err( I18n.ERR_04434 ) ); } // create buffer and add everything before start of scan byte[] buf = new byte[ str.length()/3]; int pos = 0; // start scaning until we find an escaped series of bytes for ( int i = 0; i < length; i++ ) { char c = str.charAt( i ); if ( c == '\\' ) { // we have the start of a hex escape sequence if ( isHex( str, i+1 ) && isHex ( str, i+2 ) ) { byte value = ( byte ) ( (StringTools.HEX_VALUE[str.charAt( i+1 )] << 4 ) + StringTools.HEX_VALUE[str.charAt( i+2 )] ); i+=2; buf[pos++] = value; } } else { throw new InvalidNameException( I18n.err( I18n.ERR_04435 ) ); } } return buf; } /** * Thansform an array of ASCII bytes to a string. the byte array should contains * only values in [0, 127]. * * @param bytes The byte array to transform * @return The resulting string */ public static String asciiBytesToString( byte[] bytes ) { if ( (bytes == null) || (bytes.length == 0 ) ) { return ""; } char[] result = new char[bytes.length]; for ( int i = 0; i < bytes.length; i++ ) { result[i] = (char)bytes[i]; } return new String( result ); } /** * Build an AttributeType froma byte array. An AttributeType contains * only chars within [0-9][a-z][A-Z][-.]. * * @param bytes The bytes containing the AttributeType * @return The AttributeType as a String */ public static String getType( byte[] bytes) { if ( bytes == null ) { return null; } char[] chars = new char[bytes.length]; int pos = 0; for ( byte b:bytes ) { chars[pos++] = (char)b; } return new String( chars ); } /** * * Check that a String is a valid IA5String. An IA5String contains only * char which values is between [0, 7F] * * @param str The String to check * @return <code>true</code> if the string is an IA5String or is empty, * <code>false</code> otherwise */ public static boolean isIA5String( String str ) { if ( ( str == null ) || ( str.length() == 0 ) ) { return true; } // All the chars must be in [0x00, 0x7F] for ( char c:str.toCharArray() ) { if ( ( c < 0 ) || ( c > 0x7F ) ) { return false; } } return true; } /** * * Check that a String is a valid PrintableString. A PrintableString contains only * the following set of chars : * { ' ', ''', '(', ')', '+', '-', '.', '/', [0-9], ':', '=', '?', [A-Z], [a-z]} * * @param str The String to check * @return <code>true</code> if the string is a PrintableString or is empty, * <code>false</code> otherwise */ public static boolean isPrintableString( String str ) { if ( ( str == null ) || ( str.length() == 0 ) ) { return true; } for ( char c:str.toCharArray() ) { if ( ( c > 127 ) || !IS_PRINTABLE_CHAR[ c ] ) { return false; } } return true; } /** * Check if the current char is in the unicodeSubset : all chars but * '\0', '(', ')', '*' and '\' * * @param str The string to check * @param pos Position of the current char * @return True if the current char is in the unicode subset */ public static boolean isUnicodeSubset( String str, int pos ) { if ( ( str == null ) || ( str.length() <= pos ) || ( pos < 0 ) ) { return false; } char c = str.charAt( pos ); return ( ( c > 127 ) || UNICODE_SUBSET[c] ); } /** * Check if the current char is in the unicodeSubset : all chars but * '\0', '(', ')', '*' and '\' * * @param c The char to check * @return True if the current char is in the unicode subset */ public static boolean isUnicodeSubset( char c ) { return ( ( c > 127 ) || UNICODE_SUBSET[c] ); } /** * converts the bytes of a UUID to string * * @param bytes bytes of a UUID * @return UUID in string format */ public static String uuidToString( byte[] bytes ) { if ( bytes == null || bytes.length != 16 ) { return "Invalid UUID"; } char[] hex = Hex.encodeHex( bytes ); StringBuffer sb = new StringBuffer(); sb.append( hex, 0, 8 ); sb.append( '-' ); sb.append( hex, 8, 4 ); sb.append( '-' ); sb.append( hex, 12, 4 ); sb.append( '-' ); sb.append( hex, 16, 4 ); sb.append( '-' ); sb.append( hex, 20, 12 ); return sb.toString().toLowerCase(); } /** * converts the string representation of an UUID to bytes * * @param string the string representation of an UUID * @return the bytes, null if the the syntax is not valid */ public static byte[] uuidToBytes( String string ) { if ( !new UuidSyntaxChecker().isValidSyntax( string ) ) { return null; } char[] chars = string.toCharArray(); byte[] bytes = new byte[16]; bytes[0] = getHexValue( chars[0], chars[1] ); bytes[1] = getHexValue( chars[2], chars[3] ); bytes[2] = getHexValue( chars[4], chars[5] ); bytes[3] = getHexValue( chars[6], chars[7] ); bytes[4] = getHexValue( chars[9], chars[10] ); bytes[5] = getHexValue( chars[11], chars[12] ); bytes[6] = getHexValue( chars[14], chars[15] ); bytes[7] = getHexValue( chars[16], chars[17] ); bytes[8] = getHexValue( chars[19], chars[20] ); bytes[9] = getHexValue( chars[21], chars[22] ); bytes[10] = getHexValue( chars[24], chars[25] ); bytes[11] = getHexValue( chars[26], chars[27] ); bytes[12] = getHexValue( chars[28], chars[29] ); bytes[13] = getHexValue( chars[30], chars[31] ); bytes[14] = getHexValue( chars[32], chars[33] ); bytes[15] = getHexValue( chars[34], chars[35] ); return bytes; } }
ldap/src/main/java/org/apache/directory/shared/ldap/util/StringTools.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.shared.ldap.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.naming.InvalidNameException; import org.apache.directory.shared.asn1.codec.binary.Hex; import org.apache.directory.shared.i18n.I18n; import org.apache.directory.shared.ldap.entry.BinaryValue; import org.apache.directory.shared.ldap.entry.StringValue; import org.apache.directory.shared.ldap.schema.syntaxCheckers.UuidSyntaxChecker; /** * Various string manipulation methods that are more efficient then chaining * string operations: all is done in the same buffer without creating a bunch of * string objects. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ */ public class StringTools { /** The default charset, because it's not provided by JDK 1.5 */ static String defaultCharset = null; // ~ Static fields/initializers // ----------------------------------------------------------------- /** Hex chars */ private static final byte[] HEX_CHAR = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final int UTF8_MULTI_BYTES_MASK = 0x0080; private static final int UTF8_TWO_BYTES_MASK = 0x00E0; private static final int UTF8_TWO_BYTES = 0x00C0; private static final int UTF8_THREE_BYTES_MASK = 0x00F0; private static final int UTF8_THREE_BYTES = 0x00E0; private static final int UTF8_FOUR_BYTES_MASK = 0x00F8; private static final int UTF8_FOUR_BYTES = 0x00F0; private static final int UTF8_FIVE_BYTES_MASK = 0x00FC; private static final int UTF8_FIVE_BYTES = 0x00F8; private static final int UTF8_SIX_BYTES_MASK = 0x00FE; private static final int UTF8_SIX_BYTES = 0x00FC; /** &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] */ private static final boolean[] ALPHA = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha-lower-case> ::= [0x61-0x7A] */ private static final boolean[] ALPHA_LOWER_CASE = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha-upper-case> ::= [0x41-0x5A] */ private static final boolean[] ALPHA_UPPER_CASE = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; /** &lt;alpha-digit> | &lt;digit> */ private static final boolean[] ALPHA_DIGIT = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** &lt;alpha> | &lt;digit> | '-' */ private static final boolean[] CHAR = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; /** %01-%27 %2B-%5B %5D-%7F */ private static final boolean[] UNICODE_SUBSET = { false, true, true, true, true, true, true, true, // '\0' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, // '(', ')', '*' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, // '\' true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, }; /** '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' */ private static final boolean[] DIGIT = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */ private static final boolean[] HEX = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; /** A table containing booleans when the corresponding char is printable */ private static final boolean[] IS_PRINTABLE_CHAR = { false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- false, false, false, false, false, false, false, false, // ---, ---, ---, ---, ---, ---, ---, --- true, false, false, false, false, false, false, true, // ' ', ---, ---, ---, ---, ---, ---, "'" true, true, false, true, true, true, true, true, // '(', ')', ---, '+', ',', '-', '.', '/' true, true, true, true, true, true, true, true, // '0', '1', '2', '3', '4', '5', '6', '7', true, true, true, false, false, true, false, true, // '8', '9', ':', ---, ---, '=', ---, '?' false, true, true, true, true, true, true, true, // ---, 'A', 'B', 'C', 'D', 'E', 'F', 'G', true, true, true, true, true, true, true, true, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' true, true, true, true, true, true, true, true, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' true, true, true, false, false, false, false, false, // 'X', 'Y', 'Z', ---, ---, ---, ---, --- false, true, true, true, true, true, true, true, // ---, 'a', 'b', 'c', 'd', 'e', 'f', 'g' true, true, true, true, true, true, true, true, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' true, true, true, true, true, true, true, true, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' true, true, true, false, false, false, false, false // 'x', 'y', 'z', ---, ---, ---, ---, --- }; /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */ private static final byte[] HEX_VALUE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00 -> 0F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10 -> 1F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20 -> 2F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 30 -> 3F ( 0, 1,2, 3, 4,5, 6, 7, 8, 9 ) -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 40 -> 4F ( A, B, C, D, E, F ) -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 50 -> 5F -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 // 60 -> 6F ( a, b, c, d, e, f ) }; private static final char[] TO_LOWER_CASE = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, ' ', 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, '\'', '(', ')', 0x2A, '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', 0x3B, 0x3C, '=', 0x3E, '?', 0x40, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, }; /** upperCase = 'A' .. 'Z', '0'..'9', '-' */ private static final char[] UPPER_CASE = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '-', 0, 0, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 0, 0, 0, 0, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private static final int CHAR_ONE_BYTE_MASK = 0xFFFFFF80; private static final int CHAR_TWO_BYTES_MASK = 0xFFFFF800; private static final int CHAR_THREE_BYTES_MASK = 0xFFFF0000; private static final int CHAR_FOUR_BYTES_MASK = 0xFFE00000; private static final int CHAR_FIVE_BYTES_MASK = 0xFC000000; private static final int CHAR_SIX_BYTES_MASK = 0x80000000; public static final int NOT_EQUAL = -1; // The following methods are taken from org.apache.commons.lang.StringUtils /** * The empty String <code>""</code>. * * @since 2.0 */ public static final String EMPTY = ""; /** * The empty byte[] */ public static final byte[] EMPTY_BYTES = new byte[] {}; /** * The empty String[] */ public static final String[] EMPTY_STRINGS = new String[] {}; /** * Trims several consecutive characters into one. * * @param str * the string to trim consecutive characters of * @param ch * the character to trim down * @return the newly trimmed down string */ public static final String trimConsecutiveToOne( String str, char ch ) { if ( ( null == str ) || ( str.length() == 0 ) ) { return ""; } char[] buffer = str.toCharArray(); char[] newbuf = new char[buffer.length]; int pos = 0; boolean same = false; for ( int i = 0; i < buffer.length; i++ ) { char car = buffer[i]; if ( car == ch ) { if ( same ) { continue; } else { same = true; newbuf[pos++] = car; } } else { same = false; newbuf[pos++] = car; } } return new String( newbuf, 0, pos ); } /** * A deep trim of a string remove whitespace from the ends as well as * excessive whitespace within the inside of the string between * non-whitespace characters. A deep trim reduces internal whitespace down * to a single space to perserve the whitespace separated tokenization order * of the String. * * @param string the string to deep trim. * @return the trimmed string. */ public static final String deepTrim( String string ) { return deepTrim( string, false ); } /** * This does the same thing as a trim but we also lowercase the string while * performing the deep trim within the same buffer. This saves us from * having to create multiple String and StringBuffer objects and is much * more efficient. * * @see StringTools#deepTrim( String ) */ public static final String deepTrimToLower( String string ) { return deepTrim( string, true ); } /** * Put common code to deepTrim(String) and deepTrimToLower here. * * @param str the string to deep trim * @param toLowerCase how to normalize for case: upper or lower * @return the deep trimmed string * @see StringTools#deepTrim( String ) * * TODO Replace the toCharArray() by substring manipulations */ public static final String deepTrim( String str, boolean toLowerCase ) { if ( ( null == str ) || ( str.length() == 0 ) ) { return ""; } char ch; char[] buf = str.toCharArray(); char[] newbuf = new char[buf.length]; boolean wsSeen = false; boolean isStart = true; int pos = 0; for ( int i = 0; i < str.length(); i++ ) { ch = buf[i]; // filter out all uppercase characters if ( toLowerCase && Character.isUpperCase( ch ) ) { ch = Character.toLowerCase( ch ); } // Check to see if we should add space if ( Character.isWhitespace( ch ) ) { // If the buffer has had characters added already check last // added character. Only append a spc if last character was // not whitespace. if ( wsSeen ) { continue; } else { wsSeen = true; if ( isStart ) { isStart = false; } else { newbuf[pos++] = ch; } } } else { // Add all non-whitespace wsSeen = false; isStart = false; newbuf[pos++] = ch; } } return ( pos == 0 ? "" : new String( newbuf, 0, ( wsSeen ? pos - 1 : pos ) ) ); } /** * Truncates large Strings showing a portion of the String's head and tail * with the center cut out and replaced with '...'. Also displays the total * length of the truncated string so size of '...' can be interpreted. * Useful for large strings in UIs or hex dumps to log files. * * @param str the string to truncate * @param head the amount of the head to display * @param tail the amount of the tail to display * @return the center truncated string */ public static final String centerTrunc( String str, int head, int tail ) { StringBuffer buf = null; // Return as-is if String is smaller than or equal to the head plus the // tail plus the number of characters added to the trunc representation // plus the number of digits in the string length. if ( str.length() <= ( head + tail + 7 + str.length() / 10 ) ) { return str; } buf = new StringBuffer(); buf.append( '[' ).append( str.length() ).append( "][" ); buf.append( str.substring( 0, head ) ).append( "..." ); buf.append( str.substring( str.length() - tail ) ); buf.append( ']' ); return buf.toString(); } /** * Gets a hex string from byte array. * * @param res * the byte array * @return the hex string representing the binary values in the array */ public static final String toHexString( byte[] res ) { StringBuffer buf = new StringBuffer( res.length << 1 ); for ( int ii = 0; ii < res.length; ii++ ) { String digit = Integer.toHexString( 0xFF & res[ii] ); if ( digit.length() == 1 ) { digit = '0' + digit; } buf.append( digit ); } return buf.toString().toUpperCase(); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. * * @param value The String to lowercase * @return The lowercase string */ public static final String toLowerCase( String value ) { if ( ( null == value ) || ( value.length() == 0 ) ) { return ""; } char[] chars = value.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { chars[i] = TO_LOWER_CASE[ chars[i] ]; } return new String( chars ); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. * * @param value The String to uppercase * @return The uppercase string */ public static final String toUpperCase( String value ) { if ( ( null == value ) || ( value.length() == 0 ) ) { return ""; } char[] chars = value.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { chars[i] = UPPER_CASE[ chars[i] ]; } return new String( chars ); } /** * Get byte array from hex string * * @param hexString * the hex string to convert to a byte array * @return the byte form of the hex string. */ public static final byte[] toByteArray( String hexString ) { int arrLength = hexString.length() >> 1; byte buf[] = new byte[arrLength]; for ( int ii = 0; ii < arrLength; ii++ ) { int index = ii << 1; String l_digit = hexString.substring( index, index + 2 ); buf[ii] = ( byte ) Integer.parseInt( l_digit, 16 ); } return buf; } /** * This method is used to insert HTML block dynamically * * @param source the HTML code to be processes * @param replaceNl if true '\n' will be replaced by &lt;br> * @param replaceTag if true '<' will be replaced by &lt; and '>' will be replaced * by &gt; * @param replaceQuote if true '\"' will be replaced by &quot; * @return the formated html block */ public static final String formatHtml( String source, boolean replaceNl, boolean replaceTag, boolean replaceQuote ) { StringBuffer buf = new StringBuffer(); int len = source.length(); for ( int ii = 0; ii < len; ii++ ) { char ch = source.charAt( ii ); switch ( ch ) { case '\"': if ( replaceQuote ) { buf.append( "&quot;" ); } else { buf.append( ch ); } break; case '<': if ( replaceTag ) { buf.append( "&lt;" ); } else { buf.append( ch ); } break; case '>': if ( replaceTag ) { buf.append( "&gt;" ); } else { buf.append( ch ); } break; case '\n': if ( replaceNl ) { if ( replaceTag ) { buf.append( "&lt;br&gt;" ); } else { buf.append( "<br>" ); } } else { buf.append( ch ); } break; case '\r': break; case '&': buf.append( "&amp;" ); break; default: buf.append( ch ); break; } } return buf.toString(); } /** * Creates a regular expression from an LDAP substring assertion filter * specification. * * @param initialPattern * the initial fragment before wildcards * @param anyPattern * fragments surrounded by wildcards if any * @param finalPattern * the final fragment after last wildcard if any * @return the regular expression for the substring match filter * @throws PatternSyntaxException * if a syntactically correct regular expression cannot be * compiled */ public static final Pattern getRegex( String initialPattern, String[] anyPattern, String finalPattern ) throws PatternSyntaxException { StringBuffer buf = new StringBuffer(); if ( initialPattern != null ) { buf.append( '^' ).append( Pattern.quote( initialPattern ) ); } if ( anyPattern != null ) { for ( int i = 0; i < anyPattern.length; i++ ) { buf.append( ".*" ).append( Pattern.quote( anyPattern[i] ) ); } } if ( finalPattern != null ) { buf.append( ".*" ).append( Pattern.quote( finalPattern ) ); } else { buf.append( ".*" ); } return Pattern.compile( buf.toString() ); } /** * Generates a regular expression from an LDAP substring match expression by * parsing out the supplied string argument. * * @param ldapRegex * the substring match expression * @return the regular expression for the substring match filter * @throws PatternSyntaxException * if a syntactically correct regular expression cannot be * compiled */ public static final Pattern getRegex( String ldapRegex ) throws PatternSyntaxException { if ( ldapRegex == null ) { throw new PatternSyntaxException( I18n.err( I18n.ERR_04429 ), "null", -1 ); } List<String> any = new ArrayList<String>(); String remaining = ldapRegex; int index = remaining.indexOf( '*' ); if ( index == -1 ) { throw new PatternSyntaxException( I18n.err( I18n.ERR_04430 ), remaining, -1 ); } String initialPattern = null; if ( remaining.charAt( 0 ) != '*' ) { initialPattern = remaining.substring( 0, index ); } remaining = remaining.substring( index + 1, remaining.length() ); while ( ( index = remaining.indexOf( '*' ) ) != -1 ) { any.add( remaining.substring( 0, index ) ); remaining = remaining.substring( index + 1, remaining.length() ); } String finalPattern = null; if ( !remaining.endsWith( "*" ) && remaining.length() > 0 ) { finalPattern = remaining; } if ( any.size() > 0 ) { String[] anyStrs = new String[any.size()]; for ( int i = 0; i < anyStrs.length; i++ ) { anyStrs[i] = any.get( i ); } return getRegex( initialPattern, anyStrs, finalPattern ); } return getRegex( initialPattern, null, finalPattern ); } /** * Splits apart a OS separator delimited set of paths in a string into * multiple Strings. File component path strings are returned within a List * in the order they are found in the composite path string. Optionally, a * file filter can be used to filter out path strings to control the * components returned. If the filter is null all path components are * returned. * * @param paths * a set of paths delimited using the OS path separator * @param filter * a FileFilter used to filter the return set * @return the filter accepted path component Strings in the order * encountered */ @SuppressWarnings("PMD.CollapsibleIfStatements") // Used because of comments public static final List<String> getPaths( String paths, FileFilter filter ) { int start = 0; int stop = -1; String path = null; List<String> list = new ArrayList<String>(); // Abandon with no values if paths string is null if ( paths == null || paths.trim().equals( "" ) ) { return list; } final int max = paths.length() - 1; // Loop spliting string using OS path separator: terminate // when the start index is at the end of the paths string. while ( start < max ) { stop = paths.indexOf( File.pathSeparatorChar, start ); // The is no file sep between the start and the end of the string if ( stop == -1 ) { // If we have a trailing path remaining without ending separator if ( start < max ) { // Last path is everything from start to the string's end path = paths.substring( start ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the // path only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } } break; // Exit loop no more path components left! } // There is a separator between start and the end if we got here! // start index is now at 0 or the index of last separator + 1 // stop index is now at next separator in front of start index path = paths.substring( start, stop ); // Protect against consecutive separators side by side if ( !path.trim().equals( "" ) ) { // If filter is null add path, if it is not null add the path // only if the filter accepts the path component. if ( filter == null || filter.accept( new File( path ) ) ) { list.add( path ); } } // Advance start index past separator to start of next path comp start = stop + 1; } return list; } // ~ Methods // ------------------------------------------------------------------------------------ /** * Helper function that dump a byte in hex form * * @param octet The byte to dump * @return A string representation of the byte */ public static final String dumpByte( byte octet ) { return new String( new byte[] { '0', 'x', HEX_CHAR[( octet & 0x00F0 ) >> 4], HEX_CHAR[octet & 0x000F] } ); } /** * Helper function that returns a char from an hex * * @param hex The hex to dump * @return A char representation of the hex */ public static final char dumpHex( byte hex ) { return ( char ) HEX_CHAR[hex & 0x000F]; } /** * Helper function that dump an array of bytes in hex form * * @param buffer The bytes array to dump * @return A string representation of the array of bytes */ public static final String dumpBytes( byte[] buffer ) { if ( buffer == null ) { return ""; } StringBuffer sb = new StringBuffer(); for ( int i = 0; i < buffer.length; i++ ) { sb.append( "0x" ).append( ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ) ).append( ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ) ).append( " " ); } return sb.toString(); } /** * * Helper method to render an object which can be a String or a byte[] * * @return A string representing the object */ public static String dumpObject( Object object ) { if ( object != null ) { if ( object instanceof String ) { return (String) object; } else if ( object instanceof byte[] ) { return dumpBytes( ( byte[] ) object ); } else if ( object instanceof StringValue ) { return ( ( StringValue ) object ).get(); } else if ( object instanceof BinaryValue ) { return dumpBytes( ( ( BinaryValue ) object ).get() ); } else { return "<unknown type>"; } } else { return ""; } } /** * Helper function that dump an array of bytes in hex pair form, * without '0x' and space chars * * @param buffer The bytes array to dump * @return A string representation of the array of bytes */ public static final String dumpHexPairs( byte[] buffer ) { if ( buffer == null ) { return ""; } char[] str = new char[buffer.length << 1]; for ( int i = 0, pos = 0; i < buffer.length; i++ ) { str[pos++] = ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ); str[pos++] = ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ); } return new String( str ); } /** * Return the Unicode char which is coded in the bytes at position 0. * * @param bytes The byte[] represntation of an Unicode string. * @return The first char found. */ public static final char bytesToChar( byte[] bytes ) { return bytesToChar( bytes, 0 ); } /** * Count the number of bytes needed to return an Unicode char. This can be * from 1 to 6. * * @param bytes The bytes to read * @param pos Position to start counting. It must be a valid start of a * encoded char ! * @return The number of bytes to create a char, or -1 if the encoding is * wrong. TODO : Should stop after the third byte, as a char is only * 2 bytes long. */ public static final int countBytesPerChar( byte[] bytes, int pos ) { if ( bytes == null ) { return -1; } if ( ( bytes[pos] & UTF8_MULTI_BYTES_MASK ) == 0 ) { return 1; } else if ( ( bytes[pos] & UTF8_TWO_BYTES_MASK ) == UTF8_TWO_BYTES ) { return 2; } else if ( ( bytes[pos] & UTF8_THREE_BYTES_MASK ) == UTF8_THREE_BYTES ) { return 3; } else if ( ( bytes[pos] & UTF8_FOUR_BYTES_MASK ) == UTF8_FOUR_BYTES ) { return 4; } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { return 5; } else if ( ( bytes[pos] & UTF8_SIX_BYTES_MASK ) == UTF8_SIX_BYTES ) { return 6; } else { return -1; } } /** * Return the number of bytes that hold an Unicode char. * * @param car The character to be decoded * @return The number of bytes to hold the char. TODO : Should stop after * the third byte, as a char is only 2 bytes long. */ public static final int countNbBytesPerChar( char car ) { if ( ( car & CHAR_ONE_BYTE_MASK ) == 0 ) { return 1; } else if ( ( car & CHAR_TWO_BYTES_MASK ) == 0 ) { return 2; } else if ( ( car & CHAR_THREE_BYTES_MASK ) == 0 ) { return 3; } else if ( ( car & CHAR_FOUR_BYTES_MASK ) == 0 ) { return 4; } else if ( ( car & CHAR_FIVE_BYTES_MASK ) == 0 ) { return 5; } else if ( ( car & CHAR_SIX_BYTES_MASK ) == 0 ) { return 6; } else { return -1; } } /** * Count the number of bytes included in the given char[]. * * @param chars The char array to decode * @return The number of bytes in the char array */ public static final int countBytes( char[] chars ) { if ( chars == null ) { return 0; } int nbBytes = 0; int currentPos = 0; while ( currentPos < chars.length ) { int nbb = countNbBytesPerChar( chars[currentPos] ); // If the number of bytes necessary to encode a character is // above 3, we will need two UTF-16 chars currentPos += ( nbb < 4 ? 1 : 2 ); nbBytes += nbb; } return nbBytes; } /** * Return the Unicode char which is coded in the bytes at the given * position. * * @param bytes The byte[] represntation of an Unicode string. * @param pos The current position to start decoding the char * @return The decoded char, or -1 if no char can be decoded TODO : Should * stop after the third byte, as a char is only 2 bytes long. */ public static final char bytesToChar( byte[] bytes, int pos ) { if ( bytes == null ) { return ( char ) -1; } if ( ( bytes[pos] & UTF8_MULTI_BYTES_MASK ) == 0 ) { return ( char ) bytes[pos]; } else { if ( ( bytes[pos] & UTF8_TWO_BYTES_MASK ) == UTF8_TWO_BYTES ) { // Two bytes char return ( char ) ( ( ( bytes[pos] & 0x1C ) << 6 ) + // 110x-xxyy // 10zz-zzzz // -> // 0000-0xxx // 0000-0000 ( ( bytes[pos] & 0x03 ) << 6 ) + // 110x-xxyy 10zz-zzzz // -> 0000-0000 // yy00-0000 ( bytes[pos + 1] & 0x3F ) // 110x-xxyy 10zz-zzzz -> 0000-0000 // 00zz-zzzz ); // -> 0000-0xxx yyzz-zzzz (07FF) } else if ( ( bytes[pos] & UTF8_THREE_BYTES_MASK ) == UTF8_THREE_BYTES ) { // Three bytes char return ( char ) ( // 1110-tttt 10xx-xxyy 10zz-zzzz -> tttt-0000-0000-0000 ( ( bytes[pos] & 0x0F ) << 12 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-xxxx-0000-0000 ( ( bytes[pos + 1] & 0x3C ) << 6 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-0000-yy00-0000 ( ( bytes[pos + 1] & 0x03 ) << 6 ) + // 1110-tttt 10xx-xxyy 10zz-zzzz -> 0000-0000-00zz-zzzz ( bytes[pos + 2] & 0x3F ) // -> tttt-xxxx yyzz-zzzz (FF FF) ); } else if ( ( bytes[pos] & UTF8_FOUR_BYTES_MASK ) == UTF8_FOUR_BYTES ) { // Four bytes char return ( char ) ( // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 000t-tt00 // 0000-0000 0000-0000 ( ( bytes[pos] & 0x07 ) << 18 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-00uu // 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x30 ) << 16 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // vvvv-0000 0000-0000 ( ( bytes[pos + 1] & 0x0F ) << 12 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-xxxx 0000-0000 ( ( bytes[pos + 2] & 0x3C ) << 6 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-0000 yy00-0000 ( ( bytes[pos + 2] & 0x03 ) << 6 ) + // 1111-0ttt 10uu-vvvv 10xx-xxyy 10zz-zzzz -> 0000-0000 // 0000-0000 00zz-zzzz ( bytes[pos + 3] & 0x3F ) // -> 000t-ttuu vvvv-xxxx yyzz-zzzz (1FFFFF) ); } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { // Five bytes char return ( char ) ( // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-00tt 0000-0000 0000-0000 0000-0000 ( ( bytes[pos] & 0x03 ) << 24 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 uuuu-uu00 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x3F ) << 18 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-00vv 0000-0000 0000-0000 ( ( bytes[pos + 2] & 0x30 ) << 12 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 wwww-0000 0000-0000 ( ( bytes[pos + 2] & 0x0F ) << 12 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-xxxx 0000-0000 ( ( bytes[pos + 3] & 0x3C ) << 6 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 yy00-0000 ( ( bytes[pos + 3] & 0x03 ) << 6 ) + // 1111-10tt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 00zz-zzzz ( bytes[pos + 4] & 0x3F ) // -> 0000-00tt uuuu-uuvv wwww-xxxx yyzz-zzzz (03 FF FF FF) ); } else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES ) { // Six bytes char return ( char ) ( // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 0s00-0000 0000-0000 0000-0000 0000-0000 ( ( bytes[pos] & 0x01 ) << 30 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 00tt-tttt 0000-0000 0000-0000 0000-0000 ( ( bytes[pos + 1] & 0x3F ) << 24 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 uuuu-uu00 0000-0000 0000-0000 ( ( bytes[pos + 2] & 0x3F ) << 18 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-00vv 0000-0000 0000-0000 ( ( bytes[pos + 3] & 0x30 ) << 12 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 wwww-0000 0000-0000 ( ( bytes[pos + 3] & 0x0F ) << 12 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 0000-xxxx 0000-0000 ( ( bytes[pos + 4] & 0x3C ) << 6 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy // 10zz-zzzz -> // 0000-0000 0000-0000 0000-0000 yy00-0000 ( ( bytes[pos + 4] & 0x03 ) << 6 ) + // 1111-110s 10tt-tttt 10uu-uuuu 10vv-wwww 10xx-xxyy 10zz-zzzz // -> // 0000-0000 0000-0000 0000-0000 00zz-zzzz ( bytes[pos + 5] & 0x3F ) // -> 0stt-tttt uuuu-uuvv wwww-xxxx yyzz-zzzz (7F FF FF FF) ); } else { return ( char ) -1; } } } /** * Return the Unicode char which is coded in the bytes at the given * position. * * @param car The character to be transformed to an array of bytes * * @return The byte array representing the char * * TODO : Should stop after the third byte, as a char is only 2 bytes long. */ public static final byte[] charToBytes( char car ) { byte[] bytes = new byte[countNbBytesPerChar( car )]; if ( car <= 0x7F ) { // Single byte char bytes[0] = ( byte ) car; return bytes; } else if ( car <= 0x7FF ) { // two bytes char bytes[0] = ( byte ) ( 0x00C0 + ( ( car & 0x07C0 ) >> 6 ) ); bytes[1] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); } else { // Three bytes char bytes[0] = ( byte ) ( 0x00E0 + ( ( car & 0xF000 ) >> 12 ) ); bytes[1] = ( byte ) ( 0x0080 + ( ( car & 0x0FC0 ) >> 6 ) ); bytes[2] = ( byte ) ( 0x0080 + ( car & 0x3F ) ); } return bytes; } /** * Count the number of chars included in the given byte[]. * * @param bytes The byte array to decode * @return The number of char in the byte array */ public static final int countChars( byte[] bytes ) { if ( bytes == null ) { return 0; } int nbChars = 0; int currentPos = 0; while ( currentPos < bytes.length ) { currentPos += countBytesPerChar( bytes, currentPos ); nbChars++; } return nbChars; } /** * Check if a text is present at the current position in a buffer. * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @param text The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( byte[] bytes, int index, String text ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( bytes.length <= index ) || ( index < 0 ) || ( text == null ) ) { return NOT_EQUAL; } else { try { byte[] data = text.getBytes( "UTF-8" ); return areEquals( bytes, index, data ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } } /** * Check if a text is present at the current position in a buffer. * * @param chars The buffer which contains the data * @param index Current position in the buffer * @param text The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( char[] chars, int index, String text ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( chars.length <= index ) || ( index < 0 ) || ( text == null ) ) { return NOT_EQUAL; } else { char[] data = text.toCharArray(); return areEquals( chars, index, data ); } } /** * Check if a text is present at the current position in a buffer. * * @param chars The buffer which contains the data * @param index Current position in the buffer * @param chars2 The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( char[] chars, int index, char[] chars2 ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( chars.length <= index ) || ( index < 0 ) || ( chars2 == null ) || ( chars2.length == 0 ) || ( chars2.length > ( chars.length + index ) ) ) { return NOT_EQUAL; } else { for ( int i = 0; i < chars2.length; i++ ) { if ( chars[index++] != chars2[i] ) { return NOT_EQUAL; } } return index; } } /** * Check if a text is present at the current position in another string. * * @param string The string which contains the data * @param index Current position in the string * @param text The text we want to check * @return <code>true</code> if the string contains the text. */ public static final boolean areEquals( String string, int index, String text ) { if ( ( string == null ) || ( text == null ) ) { return false; } int length1 = string.length(); int length2 = text.length(); if ( ( length1 == 0 ) || ( length1 <= index ) || ( index < 0 ) || ( length2 == 0 ) || ( length2 > ( length1 + index ) ) ) { return false; } else { return string.substring( index ).startsWith( text ); } } /** * Check if a text is present at the current position in a buffer. * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @param bytes2 The text we want to check * @return <code>true</code> if the buffer contains the text. */ public static final int areEquals( byte[] bytes, int index, byte[] bytes2 ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( bytes.length <= index ) || ( index < 0 ) || ( bytes2 == null ) || ( bytes2.length == 0 ) || ( bytes2.length > ( bytes.length + index ) ) ) { return NOT_EQUAL; } else { for ( int i = 0; i < bytes2.length; i++ ) { if ( bytes[index++] != bytes2[i] ) { return NOT_EQUAL; } } return index; } } /** * Test if the current character is equal to a specific character. This * function works only for character between 0 and 127, as it does compare a * byte and a char (which is 16 bits wide) * * @param byteArray * The buffer which contains the data * @param index * Current position in the buffer * @param car * The character we want to compare with the current buffer * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( byte[] byteArray, int index, char car ) { if ( ( byteArray == null ) || ( byteArray.length == 0 ) || ( index < 0 ) || ( index >= byteArray.length ) ) { return false; } else { return ( ( byteArray[index] == car ) ? true : false ); } } /** * Test if the current character is equal to a specific character. * * @param chars * The buffer which contains the data * @param index * Current position in the buffer * @param car * The character we want to compare with the current buffer * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( char[] chars, int index, char car ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { return ( ( chars[index] == car ) ? true : false ); } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isCharASCII( String string, int index, char car ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return string.charAt( index ) == car; } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isICharASCII( String string, int index, char car ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return ( ( string.charAt( index ) | 0x20 ) & car ) == car; } } /** * Test if the current character is equal to a specific character. * * @param string The String which contains the data * @param index Current position in the string * @param car The character we want to compare with the current string * position * @return <code>true</code> if the current character equals the given * character. */ public static final boolean isICharASCII( byte[] bytes, int index, char car ) { if ( bytes == null ) { return false; } int length = bytes.length; if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { return ( ( bytes[ index ] | 0x20 ) & car ) == car; } } /** * Test if the current character is a bit, ie 0 or 1. * * @param string * The String which contains the data * @param index * Current position in the string * @return <code>true</code> if the current character is a bit (0 or 1) */ public static final boolean isBit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); return ( ( c == '0' ) || ( c == '1' ) ); } } /** * Get the character at a given position in a string, checking fo limits * * @param string The string which contains the data * @param index Current position in the string * @return The character ar the given position, or '\0' if something went wrong */ public static final char charAt( String string, int index ) { if ( string == null ) { return '\0'; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return '\0'; } else { return string.charAt( index ) ; } } /** * Translate two chars to an hex value. The chars must be * in [a-fA-F0-9] * * @param high The high value * @param low The low value * @return A byte representation of the two chars */ public static byte getHexValue( char high, char low ) { if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) ) { return -1; } return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] ); } /** * Translate two bytes to an hex value. The bytes must be * in [0-9a-fA-F] * * @param high The high value * @param low The low value * @return A byte representation of the two bytes */ public static byte getHexValue( byte high, byte low ) { if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) ) { return -1; } return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] ); } /** * Return an hex value from a sinle char * The char must be in [0-9a-fA-F] * * @param c The char we want to convert * @return A byte between 0 and 15 */ public static byte getHexValue( char c ) { if ( ( c > 127 ) || ( c < 0 ) ) { return -1; } return HEX_VALUE[c]; } /** * Check if the current byte is an Hex Char * &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] * * @param byte The byte we want to check * @return <code>true</code> if the current byte is a Hex byte */ public static final boolean isHex( byte b ) { return ( ( b | 0x7F ) == 0x7F ) || HEX[b]; } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an Hex Char &lt;hex> ::= [0x30-0x39] | * [0x41-0x46] | [0x61-0x66] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a Hex Char */ public static final boolean isHex( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( HEX[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param bytes The buffer which contains the data * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( byte[] bytes ) { if ( ( bytes == null ) || ( bytes.length == 0 ) ) { return false; } else { return ( ( ( ( bytes[0] | 0x7F ) != 0x7F ) || !DIGIT[bytes[0]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param car the character to test * * @return <code>true</code> if the character is a Digit */ public static final boolean isDigit( char car ) { return ( car >= '0' ) && ( car <= '9' ); } /** * Test if the current byte is an Alpha character : * &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] * * @param c The byte to test * * @return <code>true</code> if the byte is an Alpha * character */ public static final boolean isAlpha( byte c ) { return ( ( c > 0 ) && ( c <= 127 ) && ALPHA[c] ); } /** * Test if the current character is an Alpha character : * &lt;alpha> ::= [0x41-0x5A] | [0x61-0x7A] * * @param c The char to test * * @return <code>true</code> if the character is an Alpha * character */ public static final boolean isAlpha( char c ) { return ( ( c > 0 ) && ( c <= 127 ) && ALPHA[c] ); } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is an Alpha character : &lt;alpha> ::= * [0x41-0x5A] | [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is an Alpha * character */ public static final boolean isAlphaASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a lowercased Alpha character : <br/> * &lt;alpha> ::= [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a lower Alpha * character */ public static final boolean isAlphaLowercaseASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_LOWER_CASE[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a uppercased Alpha character : <br/> * &lt;alpha> ::= [0x61-0x7A] * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a lower Alpha * character */ public static final boolean isAlphaUppercaseASCII( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_UPPER_CASE[c] == false ) ) { return false; } else { return true; } } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { return ( ( ( ( bytes[index] | 0x7F ) != 0x7F ) || !DIGIT[bytes[index]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { return ( ( ( chars[index] > 127 ) || !DIGIT[chars[index]] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param string The string which contains the data * @param index Current position in the string * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); return ( ( ( c > 127 ) || !DIGIT[c] ) ? false : true ); } } /** * Test if the current character is a digit &lt;digit> ::= '0' | '1' | '2' | * '3' | '4' | '5' | '6' | '7' | '8' | '9' * * @param chars The buffer which contains the data * @return <code>true</code> if the current character is a Digit */ public static final boolean isDigit( char[] chars ) { if ( ( chars == null ) || ( chars.length == 0 ) ) { return false; } else { return ( ( ( chars[0] > 127 ) || !DIGIT[chars[0]] ) ? false : true ); } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). * &lt;char> ::= &lt;alpha> | &lt;digit> * * @param string The string which contains the data * @param index Current position in the string * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigit( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( ALPHA_DIGIT[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param bytes The buffer which contains the data * @param index Current position in the buffer * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( byte[] bytes, int index ) { if ( ( bytes == null ) || ( bytes.length == 0 ) || ( index < 0 ) || ( index >= bytes.length ) ) { return false; } else { byte c = bytes[index]; if ( ( ( c | 0x7F ) != 0x7F ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param chars The buffer which contains the data * @param index Current position in the buffer * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( char[] chars, int index ) { if ( ( chars == null ) || ( chars.length == 0 ) || ( index < 0 ) || ( index >= chars.length ) ) { return false; } else { char c = chars[index]; if ( ( c > 127 ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } /** * Check if the current character is an 7 bits ASCII CHAR (between 0 and * 127). &lt;char> ::= &lt;alpha> | &lt;digit> | '-' * * @param string The string which contains the data * @param index Current position in the string * @return The position of the next character, if the current one is a CHAR. */ public static final boolean isAlphaDigitMinus( String string, int index ) { if ( string == null ) { return false; } int length = string.length(); if ( ( length == 0 ) || ( index < 0 ) || ( index >= length ) ) { return false; } else { char c = string.charAt( index ); if ( ( c > 127 ) || ( CHAR[c] == false ) ) { return false; } else { return true; } } } // Empty checks // ----------------------------------------------------------------------- /** * <p> * Checks if a String is empty ("") or null. * </p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty(&quot;&quot;) = true * StringUtils.isEmpty(&quot; &quot;) = false * StringUtils.isEmpty(&quot;bob&quot;) = false * StringUtils.isEmpty(&quot; bob &quot;) = false * </pre> * * <p> * NOTE: This method changed in Lang version 2.0. It no longer trims the * String. That functionality is available in isBlank(). * </p> * * @param str the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static final boolean isEmpty( String str ) { return str == null || str.length() == 0; } /** * Checks if a bytes array is empty or null. * * @param bytes The bytes array to check, may be null * @return <code>true</code> if the bytes array is empty or null */ public static final boolean isEmpty( byte[] bytes ) { return bytes == null || bytes.length == 0; } /** * <p> * Checks if a String is not empty ("") and not null. * </p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty(&quot;&quot;) = false * StringUtils.isNotEmpty(&quot; &quot;) = true * StringUtils.isNotEmpty(&quot;bob&quot;) = true * StringUtils.isNotEmpty(&quot; bob &quot;) = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is not empty and not null */ public static final boolean isNotEmpty( String str ) { return str != null && str.length() > 0; } /** * <p> * Removes spaces (char &lt;= 32) from both start and ends of this String, * handling <code>null</code> by returning <code>null</code>. * </p> * Trim removes start and end characters &lt;= 32. * * <pre> * StringUtils.trim(null) = null * StringUtils.trim(&quot;&quot;) = &quot;&quot; * StringUtils.trim(&quot; &quot;) = &quot;&quot; * StringUtils.trim(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trim(&quot; abc &quot;) = &quot;abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trim( String str ) { return ( isEmpty( str ) ? "" : str.trim() ); } /** * <p> * Removes spaces (char &lt;= 32) from both start and ends of this bytes * array, handling <code>null</code> by returning <code>null</code>. * </p> * Trim removes start and end characters &lt;= 32. * * <pre> * StringUtils.trim(null) = null * StringUtils.trim(&quot;&quot;) = &quot;&quot; * StringUtils.trim(&quot; &quot;) = &quot;&quot; * StringUtils.trim(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trim(&quot; abc &quot;) = &quot;abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * * @return the trimmed byte array */ public static final byte[] trim( byte[] bytes ) { if ( isEmpty( bytes ) ) { return EMPTY_BYTES; } int start = trimLeft( bytes, 0 ); int end = trimRight( bytes, bytes.length - 1 ); int length = end - start + 1; if ( length != 0 ) { byte[] newBytes = new byte[end - start + 1]; System.arraycopy( bytes, start, newBytes, 0, length ); return newBytes; } else { return EMPTY_BYTES; } } /** * <p> * Removes spaces (char &lt;= 32) from start of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trimLeft( String str ) { if ( isEmpty( str ) ) { return ""; } int start = 0; int end = str.length(); while ( ( start < end ) && ( str.charAt( start ) == ' ' ) ) { start++; } return ( start == 0 ? str : str.substring( start ) ); } /** * <p> * Removes spaces (char &lt;= 32) from start of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param chars the chars array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimLeft( char[] chars, int pos ) { if ( chars == null ) { return pos; } while ( ( pos < chars.length ) && ( chars[pos] == ' ' ) ) { pos++; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from a position in this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;,...) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;,...) = &quot;abc &quot; * </pre> * * @param string the string to be trimmed, may be null * @param pos The starting position */ public static final void trimLeft( String string, Position pos ) { if ( string == null ) { return; } int length = string.length(); while ( ( pos.start < length ) && ( string.charAt( pos.start ) == ' ' ) ) { pos.start++; } pos.end = pos.start; } /** * <p> * Removes spaces (char &lt;= 32) from a position in this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;,...) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;,...) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;,...) = &quot;abc &quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @param pos The starting position */ public static final void trimLeft( byte[] bytes, Position pos ) { if ( bytes == null ) { return; } int length = bytes.length; while ( ( pos.start < length ) && ( bytes[ pos.start ] == ' ' ) ) { pos.start++; } pos.end = pos.start; } /** * <p> * Removes spaces (char &lt;= 32) from start of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimLeft(null) = null * StringUtils.trimLeft(&quot;&quot;) = &quot;&quot; * StringUtils.trimLeft(&quot; &quot;) = &quot;&quot; * StringUtils.trimLeft(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimLeft(&quot; abc &quot;) = &quot;abc &quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first byte which is not a space, or the last * position of the array. */ public static final int trimLeft( byte[] bytes, int pos ) { if ( bytes == null ) { return pos; } while ( ( pos < bytes.length ) && ( bytes[pos] == ' ' ) ) { pos++; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from end of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static final String trimRight( String str ) { if ( isEmpty( str ) ) { return ""; } int length = str.length(); int end = length; while ( ( end > 0 ) && ( str.charAt( end - 1 ) == ' ' ) ) { if ( ( end > 1 ) && ( str.charAt( end - 2 ) == '\\' ) ) { break; } end--; } return ( end == length ? str : str.substring( 0, end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this String, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param str the String to be trimmed, may be null * @param escapedSpace The last escaped space, if any * @return the trimmed string, <code>null</code> if null String input */ public static final String trimRight( String str, int escapedSpace ) { if ( isEmpty( str ) ) { return ""; } int length = str.length(); int end = length; while ( ( end > 0 ) && ( str.charAt( end - 1 ) == ' ' ) && ( end > escapedSpace ) ) { if ( ( end > 1 ) && ( str.charAt( end - 2 ) == '\\' ) ) { break; } end--; } return ( end == length ? str : str.substring( 0, end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param chars the chars array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimRight( char[] chars, int pos ) { if ( chars == null ) { return pos; } while ( ( pos >= 0 ) && ( chars[pos - 1] == ' ' ) ) { pos--; } return pos; } /** * <p> * Removes spaces (char &lt;= 32) from end of this string, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param string the string to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the string. */ public static final String trimRight( String string, Position pos ) { if ( string == null ) { return ""; } while ( ( pos.end >= 0 ) && ( string.charAt( pos.end - 1 ) == ' ' ) ) { if ( ( pos.end > 1 ) && ( string.charAt( pos.end - 2 ) == '\\' ) ) { break; } pos.end--; } return ( pos.end == string.length() ? string : string.substring( 0, pos.end ) ); } /** * <p> * Removes spaces (char &lt;= 32) from end of this string, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the byte array. */ public static final String trimRight( byte[] bytes, Position pos ) { if ( bytes == null ) { return ""; } while ( ( pos.end >= 0 ) && ( bytes[pos.end - 1] == ' ' ) ) { if ( ( pos.end > 1 ) && ( bytes[pos.end - 2] == '\\' ) ) { break; } pos.end--; } if ( pos.end == bytes.length ) { return StringTools.utf8ToString( bytes ); } else { return StringTools.utf8ToString( bytes, pos.end ); } } /** * <p> * Removes spaces (char &lt;= 32) from end of this array, handling * <code>null</code> by returning <code>null</code>. * </p> * Trim removes start characters &lt;= 32. * * <pre> * StringUtils.trimRight(null) = null * StringUtils.trimRight(&quot;&quot;) = &quot;&quot; * StringUtils.trimRight(&quot; &quot;) = &quot;&quot; * StringUtils.trimRight(&quot;abc&quot;) = &quot;abc&quot; * StringUtils.trimRight(&quot; abc &quot;) = &quot; abc&quot; * </pre> * * @param bytes the byte array to be trimmed, may be null * @return the position of the first char which is not a space, or the last * position of the array. */ public static final int trimRight( byte[] bytes, int pos ) { if ( bytes == null ) { return pos; } while ( ( pos >= 0 ) && ( bytes[pos] == ' ' ) ) { pos--; } return pos; } // Case conversion // ----------------------------------------------------------------------- /** * <p> * Converts a String to upper case as per {@link String#toUpperCase()}. * </p> * <p> * A <code>null</code> input String returns <code>null</code>. * </p> * * <pre> * StringUtils.upperCase(null) = null * StringUtils.upperCase(&quot;&quot;) = &quot;&quot; * StringUtils.upperCase(&quot;aBc&quot;) = &quot;ABC&quot; * </pre> * * @param str the String to upper case, may be null * @return the upper cased String, <code>null</code> if null String input */ public static final String upperCase( String str ) { if ( str == null ) { return null; } return str.toUpperCase(); } /** * <p> * Converts a String to lower case as per {@link String#toLowerCase()}. * </p> * <p> * A <code>null</code> input String returns <code>null</code>. * </p> * * <pre> * StringUtils.lowerCase(null) = null * StringUtils.lowerCase(&quot;&quot;) = &quot;&quot; * StringUtils.lowerCase(&quot;aBc&quot;) = &quot;abc&quot; * </pre> * * @param str the String to lower case, may be null * @return the lower cased String, <code>null</code> if null String input */ public static final String lowerCase( String str ) { if ( str == null ) { return null; } return str.toLowerCase(); } /** * Rewrote the toLowercase method to improve performances. * In Ldap, attributesType are supposed to use ASCII chars : * 'a'-'z', 'A'-'Z', '0'-'9', '.' and '-' only. We will take * care of any other chars either. * * @param str The String to lowercase * @return The lowercase string */ public static final String lowerCaseAscii( String str ) { if ( str == null ) { return null; } char[] chars = str.toCharArray(); int pos = 0; for ( char c:chars ) { chars[pos++] = TO_LOWER_CASE[c]; } return new String( chars ); } // Equals // ----------------------------------------------------------------------- /** * <p> * Compares two Strings, returning <code>true</code> if they are equal. * </p> * <p> * <code>null</code>s are handled without exceptions. Two * <code>null</code> references are considered to be equal. The comparison * is case sensitive. * </p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, &quot;abc&quot;) = false * StringUtils.equals(&quot;abc&quot;, null) = false * StringUtils.equals(&quot;abc&quot;, &quot;abc&quot;) = true * StringUtils.equals(&quot;abc&quot;, &quot;ABC&quot;) = false * </pre> * * @see java.lang.String#equals(Object) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static final boolean equals( String str1, String str2 ) { return str1 == null ? str2 == null : str1.equals( str2 ); } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @return A String. */ public static final String utf8ToString( byte[] bytes ) { if ( bytes == null ) { return ""; } try { return new String( bytes, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @param length The length of the byte array to be converted * @return A String. */ public static final String utf8ToString( byte[] bytes, int length ) { if ( bytes == null ) { return ""; } try { return new String( bytes, 0, length, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return an UTF-8 encoded String * * @param bytes The byte array to be transformed to a String * @param start the starting position in the byte array * @param length The length of the byte array to be converted * @return A String. */ public static final String utf8ToString( byte[] bytes, int start, int length ) { if ( bytes == null ) { return ""; } try { return new String( bytes, start, length, "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Return UTF-8 encoded byte[] representation of a String * * @param string The string to be transformed to a byte array * @return The transformed byte array */ public static final byte[] getBytesUtf8( String string ) { if ( string == null ) { return new byte[0]; } try { return string.getBytes( "UTF-8" ); } catch ( UnsupportedEncodingException uee ) { // if this happens something is really strange throw new RuntimeException( uee ); } } /** * Utility method that return a String representation of a list * * @param list The list to transform to a string * @return A csv string */ public static final String listToString( List<?> list ) { if ( ( list == null ) || ( list.size() == 0 ) ) { return ""; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object elem : list ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( elem ); } return sb.toString(); } /** * Utility method that return a String representation of a set * * @param set The set to transform to a string * @return A csv string */ public static final String setToString( Set<?> set ) { if ( ( set == null ) || ( set.size() == 0 ) ) { return ""; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object elem : set ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( elem ); } return sb.toString(); } /** * Utility method that return a String representation of a list * * @param list The list to transform to a string * @param tabs The tabs to add in ffront of the elements * @return A csv string */ public static final String listToString( List<?> list, String tabs ) { if ( ( list == null ) || ( list.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); for ( Object elem : list ) { sb.append( tabs ); sb.append( elem ); sb.append( '\n' ); } return sb.toString(); } /** * Utility method that return a String representation of a map. The elements * will be represented as "key = value" * * @param map The map to transform to a string * @return A csv string */ public static final String mapToString( Map<?,?> map ) { if ( ( map == null ) || ( map.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); boolean isFirst = true; for ( Map.Entry<?, ?> entry:map.entrySet() ) { if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( entry.getKey() ); sb.append( " = '" ).append( entry.getValue() ).append( "'" ); } return sb.toString(); } /** * Utility method that return a String representation of a map. The elements * will be represented as "key = value" * * @param map The map to transform to a string * @param tabs The tabs to add in ffront of the elements * @return A csv string */ public static final String mapToString( Map<?,?> map, String tabs ) { if ( ( map == null ) || ( map.size() == 0 ) ) { return ""; } StringBuffer sb = new StringBuffer(); for ( Map.Entry<?, ?> entry:map.entrySet() ) { sb.append( tabs ); sb.append( entry.getKey() ); sb.append( " = '" ).append( entry.getValue().toString() ).append( "'\n" ); } return sb.toString(); } /** * Get the default charset * * @return The default charset */ public static final String getDefaultCharsetName() { if ( null == defaultCharset ) { try { // Try with jdk 1.5 method, if we are using a 1.5 jdk :) Method method = Charset.class.getMethod( "defaultCharset", new Class[0] ); defaultCharset = ((Charset) method.invoke( null, new Object[0]) ).name(); } catch (Exception e) { // fall back to old method defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); } } return defaultCharset; } /** * Decodes values of attributes in the DN encoded in hex into a UTF-8 * String. RFC2253 allows a DN's attribute to be encoded in hex. * The encoded value starts with a # then is followed by an even * number of hex characters. * * @param str the string to decode * @return the decoded string */ public static final String decodeHexString( String str ) throws InvalidNameException { if ( str == null || str.length() == 0 ) { throw new InvalidNameException( I18n.err( I18n.ERR_04431 ) ); } char[] chars = str.toCharArray(); if ( chars[0] != '#' ) { throw new InvalidNameException( I18n.err( I18n.ERR_04432, str ) ); } // the bytes representing the encoded string of hex // this should be ( length - 1 )/2 in size byte[] decoded = new byte[ ( chars.length - 1 ) >> 1 ]; for ( int ii = 1, jj = 0 ; ii < chars.length; ii+=2, jj++ ) { int ch = ( StringTools.HEX_VALUE[chars[ii]] << 4 ) + StringTools.HEX_VALUE[chars[ii+1]]; decoded[jj] = ( byte ) ch; } return StringTools.utf8ToString( decoded ); } /** * Convert an escaoed list of bytes to a byte[] * * @param str the string containing hex escapes * @return the converted byte[] */ public static final byte[] convertEscapedHex( String str ) throws InvalidNameException { if ( str == null ) { throw new InvalidNameException( I18n.err( I18n.ERR_04433 ) ); } int length = str.length(); if ( length == 0 ) { throw new InvalidNameException( I18n.err( I18n.ERR_04434 ) ); } // create buffer and add everything before start of scan byte[] buf = new byte[ str.length()/3]; int pos = 0; // start scaning until we find an escaped series of bytes for ( int i = 0; i < length; i++ ) { char c = str.charAt( i ); if ( c == '\\' ) { // we have the start of a hex escape sequence if ( isHex( str, i+1 ) && isHex ( str, i+2 ) ) { byte value = ( byte ) ( (StringTools.HEX_VALUE[str.charAt( i+1 )] << 4 ) + StringTools.HEX_VALUE[str.charAt( i+2 )] ); i+=2; buf[pos++] = value; } } else { throw new InvalidNameException( I18n.err( I18n.ERR_04435 ) ); } } return buf; } /** * Thansform an array of ASCII bytes to a string. the byte array should contains * only values in [0, 127]. * * @param bytes The byte array to transform * @return The resulting string */ public static String asciiBytesToString( byte[] bytes ) { if ( (bytes == null) || (bytes.length == 0 ) ) { return ""; } char[] result = new char[bytes.length]; for ( int i = 0; i < bytes.length; i++ ) { result[i] = (char)bytes[i]; } return new String( result ); } /** * Build an AttributeType froma byte array. An AttributeType contains * only chars within [0-9][a-z][A-Z][-.]. * * @param bytes The bytes containing the AttributeType * @return The AttributeType as a String */ public static String getType( byte[] bytes) { if ( bytes == null ) { return null; } char[] chars = new char[bytes.length]; int pos = 0; for ( byte b:bytes ) { chars[pos++] = (char)b; } return new String( chars ); } /** * * Check that a String is a valid IA5String. An IA5String contains only * char which values is between [0, 7F] * * @param str The String to check * @return <code>true</code> if the string is an IA5String or is empty, * <code>false</code> otherwise */ public static boolean isIA5String( String str ) { if ( ( str == null ) || ( str.length() == 0 ) ) { return true; } // All the chars must be in [0x00, 0x7F] for ( char c:str.toCharArray() ) { if ( ( c < 0 ) || ( c > 0x7F ) ) { return false; } } return true; } /** * * Check that a String is a valid PrintableString. A PrintableString contains only * the following set of chars : * { ' ', ''', '(', ')', '+', '-', '.', '/', [0-9], ':', '=', '?', [A-Z], [a-z]} * * @param str The String to check * @return <code>true</code> if the string is a PrintableString or is empty, * <code>false</code> otherwise */ public static boolean isPrintableString( String str ) { if ( ( str == null ) || ( str.length() == 0 ) ) { return true; } for ( char c:str.toCharArray() ) { if ( ( c > 127 ) || !IS_PRINTABLE_CHAR[ c ] ) { return false; } } return true; } /** * Check if the current char is in the unicodeSubset : all chars but * '\0', '(', ')', '*' and '\' * * @param str The string to check * @param pos Position of the current char * @return True if the current char is in the unicode subset */ public static boolean isUnicodeSubset( String str, int pos ) { if ( ( str == null ) || ( str.length() <= pos ) || ( pos < 0 ) ) { return false; } char c = str.charAt( pos ); return ( ( c > 127 ) || UNICODE_SUBSET[c] ); } /** * Check if the current char is in the unicodeSubset : all chars but * '\0', '(', ')', '*' and '\' * * @param c The char to check * @return True if the current char is in the unicode subset */ public static boolean isUnicodeSubset( char c ) { return ( ( c > 127 ) || UNICODE_SUBSET[c] ); } /** * converts the bytes of a UUID to string * * @param bytes bytes of a UUID * @return UUID in string format */ public static String uuidToString( byte[] bytes ) { if ( bytes == null || bytes.length != 16 ) { return "Invalid UUID"; } char[] hex = Hex.encodeHex( bytes ); StringBuffer sb = new StringBuffer(); sb.append( hex, 0, 8 ); sb.append( '-' ); sb.append( hex, 8, 4 ); sb.append( '-' ); sb.append( hex, 12, 4 ); sb.append( '-' ); sb.append( hex, 16, 4 ); sb.append( '-' ); sb.append( hex, 20, 12 ); return sb.toString().toLowerCase(); } /** * converts the string representation of an UUID to bytes * * @param string the string representation of an UUID * @return the bytes, null if the the syntax is not valid */ public static byte[] uuidToBytes( String string ) { if ( !new UuidSyntaxChecker().isValidSyntax( string ) ) { return null; } char[] chars = string.toCharArray(); byte[] bytes = new byte[16]; bytes[0] = getHexValue( chars[0], chars[1] ); bytes[1] = getHexValue( chars[2], chars[3] ); bytes[2] = getHexValue( chars[4], chars[5] ); bytes[3] = getHexValue( chars[6], chars[7] ); bytes[4] = getHexValue( chars[9], chars[10] ); bytes[5] = getHexValue( chars[11], chars[12] ); bytes[6] = getHexValue( chars[14], chars[15] ); bytes[7] = getHexValue( chars[16], chars[17] ); bytes[8] = getHexValue( chars[19], chars[20] ); bytes[9] = getHexValue( chars[21], chars[22] ); bytes[10] = getHexValue( chars[24], chars[25] ); bytes[11] = getHexValue( chars[26], chars[27] ); bytes[12] = getHexValue( chars[28], chars[29] ); bytes[13] = getHexValue( chars[30], chars[31] ); bytes[14] = getHexValue( chars[32], chars[33] ); bytes[15] = getHexValue( chars[34], chars[35] ); return bytes; } }
Don't catch RuntimeExceptions accidentally git-svn-id: a98780f44e7643575d86f056c30a4189ca15db44@951314 13f79535-47bb-0310-9956-ffa450edef68
ldap/src/main/java/org/apache/directory/shared/ldap/util/StringTools.java
Don't catch RuntimeExceptions accidentally
<ide><path>dap/src/main/java/org/apache/directory/shared/ldap/util/StringTools.java <ide> import java.io.FileFilter; <ide> import java.io.OutputStreamWriter; <ide> import java.io.UnsupportedEncodingException; <add>import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <ide> import java.nio.charset.Charset; <ide> import java.util.ArrayList; <ide> Method method = Charset.class.getMethod( "defaultCharset", new Class[0] ); <ide> defaultCharset = ((Charset) method.invoke( null, new Object[0]) ).name(); <ide> } <del> catch (Exception e) <add> catch (NoSuchMethodException e) <add> { <add> // fall back to old method <add> defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); <add> } <add> catch (InvocationTargetException e) <add> { <add> // fall back to old method <add> defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding(); <add> } <add> catch (IllegalAccessException e) <ide> { <ide> // fall back to old method <ide> defaultCharset = new OutputStreamWriter( new ByteArrayOutputStream() ).getEncoding();
Java
epl-1.0
4e630150c3b45a2837158fc6bf8e273a9239e7e4
0
ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio
package org.csstudio.opibuilder.widgets.editparts; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.csstudio.opibuilder.datadefinition.ColorMap; import org.csstudio.opibuilder.editparts.AbstractPVWidgetEditPart; import org.csstudio.opibuilder.editparts.ExecutionMode; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler; import org.csstudio.opibuilder.util.OPIColor; import org.csstudio.opibuilder.util.OPIFont; import org.csstudio.opibuilder.util.UIBundlingThread; import org.csstudio.opibuilder.visualparts.BorderFactory; import org.csstudio.opibuilder.visualparts.BorderStyle; import org.csstudio.opibuilder.widgets.figures.IntensityGraphFigure; import org.csstudio.opibuilder.widgets.figures.IntensityGraphFigure.IProfileDataChangeLisenter; import org.csstudio.opibuilder.widgets.model.IntensityGraphModel; import org.csstudio.opibuilder.widgets.model.IntensityGraphModel.AxisProperty; import org.csstudio.platform.data.IValue; import org.csstudio.platform.data.ValueUtil; import org.csstudio.platform.ui.util.CustomMediaFactory; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.linearscale.Range; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Dimension; /**The widget editpart of intensity graph widget. * @author Xihui Chen * */ public class IntensityGraphEditPart extends AbstractPVWidgetEditPart { private boolean innerTrig; @Override protected IFigure doCreateFigure() { IntensityGraphModel model = getWidgetModel(); IntensityGraphFigure graph = new IntensityGraphFigure(getExecutionMode()); graph.setMin(model.getMinimum()); graph.setMax(model.getMaximum()); graph.setDataWidth(model.getDataWidth()); graph.setDataHeight(model.getDataHeight()); graph.setColorMap(model.getColorMap()); graph.setShowRamp(model.isShowRamp()); graph.setCropLeft(model.getCropLeft()); graph.setCropRigth(model.getCropRight()); graph.setCropTop(model.getCropTOP()); graph.setCropBottom(model.getCropBottom()); //init X-Axis for(AxisProperty axisProperty : AxisProperty.values()){ String propID = IntensityGraphModel.makeAxisPropID( IntensityGraphModel.X_AXIS_ID, axisProperty.propIDPre); setAxisProperty(graph.getXAxis(), axisProperty, model.getPropertyValue(propID)); } //init Y-Axis for(AxisProperty axisProperty : AxisProperty.values()){ String propID = IntensityGraphModel.makeAxisPropID( IntensityGraphModel.Y_AXIS_ID, axisProperty.propIDPre); setAxisProperty(graph.getYAxis(), axisProperty, model.getPropertyValue(propID)); } //add profile data listener if(getExecutionMode() == ExecutionMode.RUN_MODE && (model.getHorizonProfileYPV().trim().length() >0 || model.getVerticalProfileYPV().trim().length() > 0)){ graph.addProfileDataListener(new IProfileDataChangeLisenter(){ public void profileDataChanged(double[] xProfileData, double[] yProfileData, Range xAxisRange, Range yAxisRange) { //horizontal setPVValue(IntensityGraphModel.PROP_HORIZON_PROFILE_Y_PV_NAME, xProfileData); double[] horizonXData = new double[xProfileData.length]; double d = (xAxisRange.getUpper() - xAxisRange.getLower())/(xProfileData.length-1); for(int i=0; i<xProfileData.length; i++){ horizonXData[i] = xAxisRange.getLower() + d *i; } setPVValue(IntensityGraphModel.PROP_HORIZON_PROFILE_X_PV_NAME, horizonXData); //vertical setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_Y_PV_NAME, yProfileData); double[] verticalXData = new double[yProfileData.length]; d = (yAxisRange.getUpper() - yAxisRange.getLower())/(yProfileData.length-1); for(int i=0; i<yProfileData.length; i++){ verticalXData[i] = yAxisRange.getUpper() - d*i; } setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_X_PV_NAME, verticalXData); } }); } return graph; } @Override public IntensityGraphModel getWidgetModel() { return (IntensityGraphModel)getModel(); } @Override protected void registerPropertyChangeHandlers() { innerUpdateGraphAreaSizeProperty(); registerAxisPropertyChangeHandler(); IWidgetPropertyChangeHandler handler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { if(newValue == null || !(newValue instanceof IValue)) return false; IValue value = (IValue)newValue; //if(ValueUtil.getSize(value) > 1){ ((IntensityGraphFigure)figure).setDataArray(ValueUtil.getDoubleArray(value)); //}else // ((IntensityGraphFigure)figure).setDataArray(ValueUtil.getDouble(value)); return false; } }; setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, handler); getWidgetModel().getProperty(IntensityGraphModel.PROP_MIN).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)figure).setMin((Double)evt.getNewValue()); figure.repaint(); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_MAX).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)figure).setMax((Double)evt.getNewValue()); figure.repaint(); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_STYLE).removeAllPropertyChangeListeners(); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_STYLE).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { figure.setBorder( BorderFactory.createBorder(BorderStyle.values()[(Integer)evt.getNewValue()], getWidgetModel().getBorderWidth(), getWidgetModel().getBorderColor(), getWidgetModel().getName())); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_WIDTH).removeAllPropertyChangeListeners(); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { figure.setBorder( BorderFactory.createBorder(getWidgetModel().getBorderStyle(), (Integer)evt.getNewValue(), getWidgetModel().getBorderColor(), getWidgetModel().getName())); innerUpdateGraphAreaSizeProperty(); } }); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setDataWidth((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_DATA_WIDTH, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setDataHeight((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_DATA_HEIGHT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setColorMap((ColorMap)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_COLOR_MAP, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropLeft((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_LEFT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropRigth((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_RIGHT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropTop((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_TOP, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropBottom((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_BOTTOM, handler); getWidgetModel().getProperty(IntensityGraphModel.PROP_SHOW_RAMP).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)getFigure()).setShowRamp((Boolean)evt.getNewValue()); Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); innerTrig = true; getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, getWidgetModel().getWidth() - d.width); innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ // if it is not triggered from inner innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, ((Integer)evt.getNewValue()) - d.width); innerTrig = false; // reset innerTrig to false after each inner triggering }else //if it is triggered from inner, do nothing innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_WIDTH, ((Integer)evt.getNewValue()) + d.width); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_HEIGHT).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT, ((Integer)evt.getNewValue()) - d.height); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_HEIGHT, ((Integer)evt.getNewValue()) + d.height); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); } private synchronized void innerUpdateGraphAreaSizeProperty(){ Dimension d = ((IntensityGraphFigure)figure).getGraphAreaInsets(); innerTrig = true; getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, getWidgetModel().getSize().width - d.width); innerTrig = true; // recover innerTrig getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT, getWidgetModel().getSize().height - d.height); innerTrig = false; // reset innerTrig to false after each inner triggering } private void registerAxisPropertyChangeHandler(){ for(String axisID : new String[]{IntensityGraphModel.X_AXIS_ID, IntensityGraphModel.Y_AXIS_ID}){ for(AxisProperty axisProperty : AxisProperty.values()){ final IWidgetPropertyChangeHandler handler = new AxisPropertyChangeHandler( axisID.equals(IntensityGraphModel.X_AXIS_ID)? ((IntensityGraphFigure)getFigure()).getXAxis(): ((IntensityGraphFigure)getFigure()).getYAxis(), axisProperty); //must use listener instead of handler because the prop sheet need to be //refreshed immediately. getWidgetModel().getProperty(IntensityGraphModel.makeAxisPropID( axisID, axisProperty.propIDPre)). addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { handler.handleChange(evt.getOldValue(), evt.getNewValue(), getFigure()); UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { getFigure().repaint(); } }); } }); } } } private void setAxisProperty(Axis axis, AxisProperty axisProperty, Object newValue){ switch (axisProperty) { case TITLE: axis.setTitle((String)newValue); break; case AXIS_COLOR: axis.setForegroundColor(CustomMediaFactory.getInstance().getColor(((OPIColor)newValue).getRGBValue())); break; case MAX: axis.setRange(axis.getRange().getLower(), (Double)newValue); break; case MIN: axis.setRange((Double)newValue, axis.getRange().getUpper()); break; case TITLE_FONT: axis.setTitleFont(CustomMediaFactory.getInstance().getFont( ((OPIFont)newValue).getFontData())); break; case MAJOR_TICK_STEP_HINT: axis.setMajorTickMarkStepHint((Integer)newValue); break; case SHOW_MINOR_TICKS: axis.setMinorTicksVisible((Boolean)newValue); break; case VISIBLE: axis.setVisible((Boolean)newValue); break; default: break; } } @Override public double[] getValue() { return ((IntensityGraphFigure)getFigure()).getDataArray(); } @Override public void setValue(Object value) { if(value instanceof double[] || value instanceof Double[]){ ((IntensityGraphFigure)getFigure()).setDataArray((double[]) value); } } @Override public void deactivate() { ((IntensityGraphFigure)getFigure()).dispose(); super.deactivate(); } class AxisPropertyChangeHandler implements IWidgetPropertyChangeHandler { private AxisProperty axisProperty; private Axis axis; public AxisPropertyChangeHandler(Axis axis, AxisProperty axisProperty) { this.axis = axis; this.axisProperty = axisProperty; } public boolean handleChange(Object oldValue, Object newValue, IFigure refreshableFigure) { setAxisProperty(axis, axisProperty, newValue); innerTrig = true; innerUpdateGraphAreaSizeProperty(); axis.revalidate(); return true; } } }
applications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/editparts/IntensityGraphEditPart.java
package org.csstudio.opibuilder.widgets.editparts; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.csstudio.opibuilder.datadefinition.ColorMap; import org.csstudio.opibuilder.editparts.AbstractPVWidgetEditPart; import org.csstudio.opibuilder.editparts.ExecutionMode; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler; import org.csstudio.opibuilder.util.OPIColor; import org.csstudio.opibuilder.util.OPIFont; import org.csstudio.opibuilder.util.UIBundlingThread; import org.csstudio.opibuilder.visualparts.BorderFactory; import org.csstudio.opibuilder.visualparts.BorderStyle; import org.csstudio.opibuilder.widgets.figures.IntensityGraphFigure; import org.csstudio.opibuilder.widgets.figures.IntensityGraphFigure.IProfileDataChangeLisenter; import org.csstudio.opibuilder.widgets.model.IntensityGraphModel; import org.csstudio.opibuilder.widgets.model.IntensityGraphModel.AxisProperty; import org.csstudio.platform.data.IValue; import org.csstudio.platform.data.ValueUtil; import org.csstudio.platform.ui.util.CustomMediaFactory; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.linearscale.Range; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Dimension; /**The widget editpart of intensity graph widget. * @author Xihui Chen * */ public class IntensityGraphEditPart extends AbstractPVWidgetEditPart { private boolean innerTrig; @Override protected IFigure doCreateFigure() { IntensityGraphModel model = getWidgetModel(); IntensityGraphFigure graph = new IntensityGraphFigure(getExecutionMode()); graph.setMin(model.getMinimum()); graph.setMax(model.getMaximum()); graph.setDataWidth(model.getDataWidth()); graph.setDataHeight(model.getDataHeight()); graph.setColorMap(model.getColorMap()); graph.setShowRamp(model.isShowRamp()); graph.setCropLeft(model.getCropLeft()); graph.setCropRigth(model.getCropRight()); graph.setCropTop(model.getCropTOP()); graph.setCropBottom(model.getCropBottom()); //init X-Axis for(AxisProperty axisProperty : AxisProperty.values()){ String propID = IntensityGraphModel.makeAxisPropID( IntensityGraphModel.X_AXIS_ID, axisProperty.propIDPre); setAxisProperty(graph.getXAxis(), axisProperty, model.getPropertyValue(propID)); } //init Y-Axis for(AxisProperty axisProperty : AxisProperty.values()){ String propID = IntensityGraphModel.makeAxisPropID( IntensityGraphModel.Y_AXIS_ID, axisProperty.propIDPre); setAxisProperty(graph.getYAxis(), axisProperty, model.getPropertyValue(propID)); } //add profile data listener if(getExecutionMode() == ExecutionMode.RUN_MODE && (model.getHorizonProfileYPV().trim().length() >0 || model.getVerticalProfileYPV().trim().length() > 0)){ graph.addProfileDataListener(new IProfileDataChangeLisenter(){ public void profileDataChanged(double[] xProfileData, double[] yProfileData, Range xAxisRange, Range yAxisRange) { //horizontal setPVValue(IntensityGraphModel.PROP_HORIZON_PROFILE_Y_PV_NAME, xProfileData); double[] horizonXData = new double[xProfileData.length]; double d = (xAxisRange.getUpper() - xAxisRange.getLower())/xProfileData.length; for(int i=0; i<xProfileData.length; i++){ horizonXData[i] = xAxisRange.getLower() + d *i; } setPVValue(IntensityGraphModel.PROP_HORIZON_PROFILE_X_PV_NAME, horizonXData); //vertical setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_Y_PV_NAME, yProfileData); double[] verticalXData = new double[yProfileData.length]; d = (yAxisRange.getUpper() - yAxisRange.getLower())/yProfileData.length; for(int i=0; i<yProfileData.length; i++){ verticalXData[i] = yAxisRange.getLower() + d *i; } setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_X_PV_NAME, verticalXData); } }); } return graph; } @Override public IntensityGraphModel getWidgetModel() { return (IntensityGraphModel)getModel(); } @Override protected void registerPropertyChangeHandlers() { innerUpdateGraphAreaSizeProperty(); registerAxisPropertyChangeHandler(); IWidgetPropertyChangeHandler handler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { if(newValue == null || !(newValue instanceof IValue)) return false; IValue value = (IValue)newValue; //if(ValueUtil.getSize(value) > 1){ ((IntensityGraphFigure)figure).setDataArray(ValueUtil.getDoubleArray(value)); //}else // ((IntensityGraphFigure)figure).setDataArray(ValueUtil.getDouble(value)); return false; } }; setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, handler); getWidgetModel().getProperty(IntensityGraphModel.PROP_MIN).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)figure).setMin((Double)evt.getNewValue()); figure.repaint(); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_MAX).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)figure).setMax((Double)evt.getNewValue()); figure.repaint(); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_STYLE).removeAllPropertyChangeListeners(); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_STYLE).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { figure.setBorder( BorderFactory.createBorder(BorderStyle.values()[(Integer)evt.getNewValue()], getWidgetModel().getBorderWidth(), getWidgetModel().getBorderColor(), getWidgetModel().getName())); innerUpdateGraphAreaSizeProperty(); } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_WIDTH).removeAllPropertyChangeListeners(); getWidgetModel().getProperty(IntensityGraphModel.PROP_BORDER_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { figure.setBorder( BorderFactory.createBorder(getWidgetModel().getBorderStyle(), (Integer)evt.getNewValue(), getWidgetModel().getBorderColor(), getWidgetModel().getName())); innerUpdateGraphAreaSizeProperty(); } }); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setDataWidth((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_DATA_WIDTH, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setDataHeight((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_DATA_HEIGHT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setColorMap((ColorMap)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_COLOR_MAP, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropLeft((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_LEFT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropRigth((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_RIGHT, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropTop((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_TOP, handler); handler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { ((IntensityGraphFigure)figure).setCropBottom((Integer)newValue); return true; } }; setPropertyChangeHandler(IntensityGraphModel.PROP_CROP_BOTTOM, handler); getWidgetModel().getProperty(IntensityGraphModel.PROP_SHOW_RAMP).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { ((IntensityGraphFigure)getFigure()).setShowRamp((Boolean)evt.getNewValue()); Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); innerTrig = true; getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, getWidgetModel().getWidth() - d.width); innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ // if it is not triggered from inner innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, ((Integer)evt.getNewValue()) - d.width); innerTrig = false; // reset innerTrig to false after each inner triggering }else //if it is triggered from inner, do nothing innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_WIDTH, ((Integer)evt.getNewValue()) + d.width); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_HEIGHT).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT, ((Integer)evt.getNewValue()) - d.height); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); getWidgetModel().getProperty(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT).addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!innerTrig){ innerTrig = true; Dimension d = ((IntensityGraphFigure)getFigure()).getGraphAreaInsets(); getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_HEIGHT, ((Integer)evt.getNewValue()) + d.height); innerTrig = false; // reset innerTrig to false after each inner triggering }else innerTrig = false; } }); } private synchronized void innerUpdateGraphAreaSizeProperty(){ Dimension d = ((IntensityGraphFigure)figure).getGraphAreaInsets(); innerTrig = true; getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_WIDTH, getWidgetModel().getSize().width - d.width); innerTrig = true; // recover innerTrig getWidgetModel().setPropertyValue(IntensityGraphModel.PROP_GRAPH_AREA_HEIGHT, getWidgetModel().getSize().height - d.height); innerTrig = false; // reset innerTrig to false after each inner triggering } private void registerAxisPropertyChangeHandler(){ for(String axisID : new String[]{IntensityGraphModel.X_AXIS_ID, IntensityGraphModel.Y_AXIS_ID}){ for(AxisProperty axisProperty : AxisProperty.values()){ final IWidgetPropertyChangeHandler handler = new AxisPropertyChangeHandler( axisID.equals(IntensityGraphModel.X_AXIS_ID)? ((IntensityGraphFigure)getFigure()).getXAxis(): ((IntensityGraphFigure)getFigure()).getYAxis(), axisProperty); //must use listener instead of handler because the prop sheet need to be //refreshed immediately. getWidgetModel().getProperty(IntensityGraphModel.makeAxisPropID( axisID, axisProperty.propIDPre)). addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { handler.handleChange(evt.getOldValue(), evt.getNewValue(), getFigure()); UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { getFigure().repaint(); } }); } }); } } } private void setAxisProperty(Axis axis, AxisProperty axisProperty, Object newValue){ switch (axisProperty) { case TITLE: axis.setTitle((String)newValue); break; case AXIS_COLOR: axis.setForegroundColor(CustomMediaFactory.getInstance().getColor(((OPIColor)newValue).getRGBValue())); break; case MAX: axis.setRange(axis.getRange().getLower(), (Double)newValue); break; case MIN: axis.setRange((Double)newValue, axis.getRange().getUpper()); break; case TITLE_FONT: axis.setTitleFont(CustomMediaFactory.getInstance().getFont( ((OPIFont)newValue).getFontData())); break; case MAJOR_TICK_STEP_HINT: axis.setMajorTickMarkStepHint((Integer)newValue); break; case SHOW_MINOR_TICKS: axis.setMinorTicksVisible((Boolean)newValue); break; case VISIBLE: axis.setVisible((Boolean)newValue); break; default: break; } } @Override public double[] getValue() { return ((IntensityGraphFigure)getFigure()).getDataArray(); } @Override public void setValue(Object value) { if(value instanceof double[] || value instanceof Double[]){ ((IntensityGraphFigure)getFigure()).setDataArray((double[]) value); } } @Override public void deactivate() { ((IntensityGraphFigure)getFigure()).dispose(); super.deactivate(); } class AxisPropertyChangeHandler implements IWidgetPropertyChangeHandler { private AxisProperty axisProperty; private Axis axis; public AxisPropertyChangeHandler(Axis axis, AxisProperty axisProperty) { this.axis = axis; this.axisProperty = axisProperty; } public boolean handleChange(Object oldValue, Object newValue, IFigure refreshableFigure) { setAxisProperty(axis, axisProperty, newValue); innerTrig = true; innerUpdateGraphAreaSizeProperty(); axis.revalidate(); return true; } } }
bug fix
applications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/editparts/IntensityGraphEditPart.java
bug fix
<ide><path>pplications/plugins/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/editparts/IntensityGraphEditPart.java <ide> //horizontal <ide> setPVValue(IntensityGraphModel.PROP_HORIZON_PROFILE_Y_PV_NAME, xProfileData); <ide> double[] horizonXData = new double[xProfileData.length]; <del> double d = (xAxisRange.getUpper() - xAxisRange.getLower())/xProfileData.length; <add> double d = (xAxisRange.getUpper() - xAxisRange.getLower())/(xProfileData.length-1); <ide> for(int i=0; i<xProfileData.length; i++){ <ide> horizonXData[i] = xAxisRange.getLower() + d *i; <ide> } <ide> //vertical <ide> setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_Y_PV_NAME, yProfileData); <ide> double[] verticalXData = new double[yProfileData.length]; <del> d = (yAxisRange.getUpper() - yAxisRange.getLower())/yProfileData.length; <add> d = (yAxisRange.getUpper() - yAxisRange.getLower())/(yProfileData.length-1); <ide> for(int i=0; i<yProfileData.length; i++){ <del> verticalXData[i] = yAxisRange.getLower() + d *i; <add> verticalXData[i] = yAxisRange.getUpper() - d*i; <ide> } <ide> setPVValue(IntensityGraphModel.PROP_VERTICAL_PROFILE_X_PV_NAME, verticalXData); <ide> }
Java
apache-2.0
96de827889412df8103d2d2483a9a2140867b177
0
szhem/camel-osgi
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.util; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * The {@code OsgiServiceCollection} is OSGi service dynamic collection that allows iterating while the * underlying storage is being shrunk/expanded. This collection is read-only as its content is being retrieved * dynamically from the OSGi platform. * <p/> * This collection and its iterators are thread-safe. That is, multiple threads can access the collection. However, * since the collection is read-only, it cannot be modified by the client. * <p/> * {@link #startTracking()} method must be called prior to track for the OSGi services. {@link #stopTracking} * method must be called to release all the associated resources. */ public class OsgiServiceCollection<E> implements Collection<E> { protected final DynamicCollection<E> services; protected final Map<Long, E> idToService; protected final Object lock = new Object(); protected final BundleContext bundleContext; protected final String filter; protected final ServiceListener listener; protected final ClassLoader fallbackClassLoader; protected final OsgiProxyCreator proxyCreator; /** * Create an instance of {@code OsgiServiceCollection}. * * @param bundleContext the {@link BundleContext} instance to look for the services that match the specified filter * @param filter OSGi instance to lookup OSGi services * @param fallbackClassLoader {@code ClassLoader} to load classes and resources in the case when these classes and * * resources cannot be loaded by means of bundle associated with the given bundleContext * @param proxyCreator an instance of {@link OsgiProxyCreator} to wrap services registered in the OSGi registry */ public OsgiServiceCollection(BundleContext bundleContext, String filter, ClassLoader fallbackClassLoader, OsgiProxyCreator proxyCreator) { this(bundleContext, filter, fallbackClassLoader, proxyCreator, new DynamicCollection<E>()); } /** * Create an instance of {@code OsgiServiceCollection}. * * @param bundleContext the {@link BundleContext} instance to look for the services that match the specified filter * @param filter OSGi filter to lookup OSGi services * @param fallbackClassLoader {@code ClassLoader} to load classes and resources in the case when these classes and * * resources cannot be loaded by means of bundle associated with the given bundleContext * @param proxyCreator an instance of {@link OsgiProxyCreator} to wrap services registered in the OSGi registry * @param backed the backed dynamic collection to hold proxies for OSGi services */ public OsgiServiceCollection(BundleContext bundleContext, String filter, ClassLoader fallbackClassLoader, OsgiProxyCreator proxyCreator, DynamicCollection<E> backed) { this.bundleContext = bundleContext; this.filter = filter; this.fallbackClassLoader = fallbackClassLoader; this.proxyCreator = proxyCreator; this.services = backed; this.idToService = new HashMap<Long, E>(); this.listener = new ServiceInstanceListener(); } /** * Start tracking for OSGi services. * * @throws IllegalStateException if this collection was initialized with invalid OSGi filter */ public void startTracking() { try { bundleContext.addServiceListener(listener, filter); ServiceReference[] alreadyDefined = bundleContext.getServiceReferences(null, filter); if(alreadyDefined != null) { for(ServiceReference ref : alreadyDefined) { listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref)); } } } catch (InvalidSyntaxException e) { throw new IllegalStateException(e); } } /** * Stops tracking for OSGi services releasing all obtained resource while starting tracking. */ public void stopTracking() { bundleContext.removeServiceListener(listener); synchronized (lock) { for (E service : services) { listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ((OsgiProxy) service).getReference())); } } } @Override public Iterator<E> iterator() { return new OsgiServiceIterator(); } @Override public int size() { return services.size(); } @Override public String toString() { return services.toString(); } /* mutators are forbidden */ @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } @Override public boolean add(Object o) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } @Override public boolean contains(Object o) { return services.contains(o); } @Override public boolean containsAll(Collection c) { return services.containsAll(c); } @Override public boolean isEmpty() { return size() == 0; } @Override public Object[] toArray() { return services.toArray(); } @SuppressWarnings("SuspiciousToArrayCall") @Override public <T> T[] toArray(T[] array) { return services.toArray(array); } protected class ServiceInstanceListener implements ServiceListener { @Override public void serviceChanged(ServiceEvent event) { ServiceReference ref = event.getServiceReference(); Long serviceID = (Long) ref.getProperty(Constants.SERVICE_ID); switch (event.getType()) { case ServiceEvent.REGISTERED: case ServiceEvent.MODIFIED: synchronized (lock) { E service = (E) proxyCreator.createProxy( bundleContext, ref, new BundleDelegatingClassLoader(ref.getBundle(), fallbackClassLoader)); idToService.put(serviceID, service); services.add(service); } break; case ServiceEvent.UNREGISTERING: case ServiceEvent.MODIFIED_ENDMATCH: synchronized (lock) { E service = idToService.remove(serviceID); if (service != null) { services.remove(service); } bundleContext.ungetService(ref); } break; default: throw new IllegalArgumentException("unsupported event type: " + event); } } } protected class OsgiServiceIterator implements Iterator<E> { private final Iterator<E> iter = services.iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @SuppressWarnings("unchecked") public E next() { return iter.next(); } @Override public void remove() { // mutators are forbidden throw new UnsupportedOperationException(); } } }
src/main/java/org/apache/camel/osgi/service/util/OsgiServiceCollection.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.util; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * The {@code OsgiServiceCollection} is OSGi service dynamic collection that allows iterating while the * underlying storage is being shrunk/expanded. This collection is read-only as its content is being retrieved * dynamically from the OSGi platform. * <p/> * This collection and its iterators are thread-safe. That is, multiple threads can access the collection. However, * since the collection is read-only, it cannot be modified by the client. * <p/> * {@link #startTracking()} method must be called prior to track for the OSGi services. {@link #stopTracking} * method must be called to release all the associated resources. */ public class OsgiServiceCollection<E> implements Collection<E> { protected final DynamicCollection<E> services; protected final Map<Long, E> idToService; protected final Object lock = new Object(); protected final BundleContext bundleContext; protected final String filter; protected final ServiceListener listener; protected final ClassLoader fallbackClassLoader; protected final OsgiProxyCreator proxyCreator; /** * Create an instance of {@code OsgiServiceCollection}. * * @param bundleContext the {@link BundleContext} instance to look for the services that match the specified filter * @param filter OSGi instance to lookup OSGi services * @param fallbackClassLoader {@code ClassLoader} to load classes and resources in the case when these classes and * * resources cannot be loaded by means of bundle associated with the given bundleContext * @param proxyCreator an instance of {@link OsgiProxyCreator} to wrap services registered in the OSGi registry */ public OsgiServiceCollection(BundleContext bundleContext, String filter, ClassLoader fallbackClassLoader, OsgiProxyCreator proxyCreator) { this(bundleContext, filter, fallbackClassLoader, proxyCreator, new DynamicCollection<E>()); } /** * Create an instance of {@code OsgiServiceCollection}. * * @param bundleContext the {@link BundleContext} instance to look for the services that match the specified filter * @param filter OSGi filter to lookup OSGi services * @param fallbackClassLoader {@code ClassLoader} to load classes and resources in the case when these classes and * * resources cannot be loaded by means of bundle associated with the given bundleContext * @param proxyCreator an instance of {@link OsgiProxyCreator} to wrap services registered in the OSGi registry * @param backed the backed dynamic collection to hold proxies for OSGi services */ public OsgiServiceCollection(BundleContext bundleContext, String filter, ClassLoader fallbackClassLoader, OsgiProxyCreator proxyCreator, DynamicCollection<E> backed) { this.bundleContext = bundleContext; this.filter = filter; this.fallbackClassLoader = fallbackClassLoader; this.proxyCreator = proxyCreator; this.services = backed; this.idToService = new HashMap<Long, E>(); this.listener = new ServiceInstanceListener(); } /** * Start tracking for OSGi services. * * @throws IllegalStateException if this collection was initialized with invalid OSGi filter */ public void startTracking() { try { bundleContext.addServiceListener(listener, filter); ServiceReference[] alreadyDefined = bundleContext.getServiceReferences(null, filter); if(alreadyDefined != null) { for(ServiceReference ref : alreadyDefined) { listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref)); } } } catch (InvalidSyntaxException e) { throw new IllegalStateException(e); } } /** * Stops tracking for OSGi services releasing all obtained resource while starting tracking. */ public void stopTracking() { bundleContext.removeServiceListener(listener); synchronized (lock) { for (E service : services) { listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ((OsgiProxy) service).getReference())); } } } @Override public Iterator<E> iterator() { return new OsgiServiceIterator(); } @Override public int size() { return services.size(); } @Override public String toString() { return services.toString(); } /* mutators are forbidden */ @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } @Override public boolean add(Object o) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } @Override public boolean contains(Object o) { return services.contains(o); } @Override public boolean containsAll(Collection c) { return services.containsAll(c); } @Override public boolean isEmpty() { return size() == 0; } @Override public Object[] toArray() { return services.toArray(); } @SuppressWarnings("SuspiciousToArrayCall") @Override public <T> T[] toArray(T[] array) { return services.toArray(array); } protected class ServiceInstanceListener implements ServiceListener { @Override public void serviceChanged(ServiceEvent event) { ServiceReference ref = event.getServiceReference(); Long serviceID = (Long) ref.getProperty(Constants.SERVICE_ID); switch (event.getType()) { case ServiceEvent.REGISTERED: case ServiceEvent.MODIFIED: synchronized (lock) { E service = proxyCreator.createProxy( bundleContext, ref, new BundleDelegatingClassLoader(ref.getBundle(), fallbackClassLoader)); idToService.put(serviceID, service); services.add(service); } break; case ServiceEvent.UNREGISTERING: case ServiceEvent.MODIFIED_ENDMATCH: synchronized (lock) { E service = idToService.remove(serviceID); if (service != null) { services.remove(service); } bundleContext.ungetService(ref); } break; default: throw new IllegalArgumentException("unsupported event type: " + event); } } } protected class OsgiServiceIterator implements Iterator<E> { private final Iterator<E> iter = services.iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @SuppressWarnings("unchecked") public E next() { return iter.next(); } @Override public void remove() { // mutators are forbidden throw new UnsupportedOperationException(); } } }
casting proxied service to collection element type
src/main/java/org/apache/camel/osgi/service/util/OsgiServiceCollection.java
casting proxied service to collection element type
<ide><path>rc/main/java/org/apache/camel/osgi/service/util/OsgiServiceCollection.java <ide> case ServiceEvent.REGISTERED: <ide> case ServiceEvent.MODIFIED: <ide> synchronized (lock) { <del> E service = proxyCreator.createProxy( <add> E service = (E) proxyCreator.createProxy( <ide> bundleContext, ref, new BundleDelegatingClassLoader(ref.getBundle(), fallbackClassLoader)); <ide> idToService.put(serviceID, service); <ide> services.add(service);
Java
mit
436703a16121ae04f3c6e641ed135845a46ccfbb
0
TouchBoarder/material-dialogs,simple88/material-dialogs,jaohoang/material-dialogs,hister/material-dialogs,nxp1986/material-dialogs,tmxdyf/material-dialogs,Heart2009/material-dialogs,awesome-niu/material-dialogs,zh-kevin/material-dialogs,Cryhelyxx/material-dialogs,fortunatey/material-dialogs,nono9119/material-dialogs,lcyluo/material-dialogs,fortunatey/material-dialogs,kimok0508/material-dialogs,worldline-spain/material-dialogs,GavinThePacMan/material-dialogs,joshfriend/material-dialogs,chengkaizone/material-dialogs,joshfriend/material-dialogs,treejames/material-dialogs,Papuh/material-dialogs,GG-YC/material-dialogs,jehad-suliman/material-dialogs,zttjava/material-dialogs,hzsweers/material-dialogs,awesome-niu/material-dialogs,Papuh/material-dialogs,nxp1986/material-dialogs,huhu/material-dialogs,ganfra/material-dialogs,afollestad/material-dialogs,Ajk2rxKamehameha/material-dialogs,gao746700783/material-dialogs,oeager/material-dialogs,LeonardoPhysh/material-dialogs,Dreezydraig/material-dialogs,simple88/material-dialogs,GavinThePacMan/material-dialogs,Ryan---Yang/material-dialogs,androidgilbert/material-dialogs,1nv4d3r5/material-dialogs,marcoaros/material-dialogs,Arisono/material-dialogs,lcyluo/material-dialogs,cnbin/material-dialogs,RyanTech/material-dialogs,marcoaros/material-dialogs,chengkaizone/material-dialogs,hesling/material-dialogs,Arisono/material-dialogs,umitems/material-dialogs,playerchenhe/material-dialogs,huhu/material-dialogs,danirb/material-dialogs,mingtang1079/material-dialogs,tsdl2013/material-dialogs,mingtang1079/material-dialogs,TonyTangAndroid/material-dialogs,PDDStudio/material-dialogs,Cryhelyxx/material-dialogs,chengfangpeng/material-dialogs,1nv4d3r5/material-dialogs,AstrDev/material-dialogs,hesling/material-dialogs,MonoCloud/material-dialogs,worldline-spain/material-dialogs,maitho/material-dialogs,nono9119/material-dialogs,asrin475/material-dialogs,AstrDev/material-dialogs,AndyScherzinger/material-dialogs,androiddream/material-dialogs,java02014/material-dialogs,elsennov/material-dialogs,Heart2009/material-dialogs,AChep/material-dialogs,DanielyBotelho/material-dialogs,sambulosenda/material-dialogs,yoslabs/material-dialogs,sambulosenda/material-dialogs,ganfra/material-dialogs,cnbin/material-dialogs,llulek/material-dialogs,treejames/material-dialogs,hejunbinlan/material-dialogs,playerchenhe/material-dialogs,greenaddress/material-dialogs,Bloody-Badboy/material-dialogs,generalzou/material-dialogs,danirb/material-dialogs,AndyScherzinger/material-dialogs,RyanTech/material-dialogs,mychaelgo/material-dialogs,LeonardoPhysh/material-dialogs,zttjava/material-dialogs,zh-kevin/material-dialogs,elsennov/material-dialogs,kimok0508/material-dialogs,tmxdyf/material-dialogs,greenaddress/material-dialogs,TigerYao/material-dialogs,Bloody-Badboy/material-dialogs,umitems/material-dialogs,AChep/material-dialogs,asrin475/material-dialogs,PaulWoitaschek/material-dialogs,yuchuangu85/material-dialogs,java02014/material-dialogs,PDDStudio/material-dialogs,Ajk2rxKamehameha/material-dialogs,oeager/material-dialogs,hejunbinlan/material-dialogs,Ryan---Yang/material-dialogs,PaulWoitaschek/material-dialogs,yoslabs/material-dialogs,TouchBoarder/material-dialogs,jaohoang/material-dialogs,llulek/material-dialogs,GG-YC/material-dialogs,generalzou/material-dialogs,tsdl2013/material-dialogs,androidgilbert/material-dialogs,maitho/material-dialogs,MonoCloud/material-dialogs,hzsweers/material-dialogs,DanielyBotelho/material-dialogs,gao746700783/material-dialogs,yuchuangu85/material-dialogs,jehad-suliman/material-dialogs,chengfangpeng/material-dialogs,Dreezydraig/material-dialogs,androiddream/material-dialogs,TigerYao/material-dialogs,MaTriXy/material-dialogs,mychaelgo/material-dialogs
package com.afollestad.materialdialogs.prefs; import android.annotation.TargetApi; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.preference.MultiSelectListPreference; import android.util.AttributeSet; import android.view.View; import com.afollestad.materialdialogs.MaterialDialog; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This class only works on Honeycomb (API 11) and above. * * @author Aidan Follestad (afollestad) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MaterialMultiSelectListPreference extends MultiSelectListPreference { private Context context; private MaterialDialog mDialog; public MaterialMultiSelectListPreference(Context context) { this(context, null); } public MaterialMultiSelectListPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context); } @Override public void setEntries(CharSequence[] entries) { super.setEntries(entries); if (mDialog != null) mDialog.setItems(entries); } private void init(Context context) { this.context = context; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) setWidgetLayoutResource(0); } @Override protected void showDialog(Bundle state) { List<Integer> indicies = new ArrayList<>(); for (String s : getValues()) { int index = findIndexOfValue(s); if(index >= 0) { indicies.add(findIndexOfValue(s)); } } MaterialDialog.Builder builder = new MaterialDialog.Builder(context) .title(getDialogTitle()) .content(getDialogMessage()) .icon(getDialogIcon()) .negativeText(getNegativeButtonText()) .positiveText(getPositiveButtonText()) .items(getEntries()) .itemsCallbackMultiChoice(indicies.toArray(new Integer[indicies.size()]), new MaterialDialog.ListCallbackMulti() { @Override public void onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) { onClick(null, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); final Set<String> values = new HashSet<>(); for (CharSequence s : text) values.add((String) s); if (callChangeListener(values)) setValues(values); } }) .dismissListener(this); final View contentView = onCreateDialogView(); if (contentView != null) { onBindDialogView(contentView); builder.customView(contentView, false); } else { builder.content(getDialogMessage()); } mDialog = builder.show(); } }
library/src/main/java/com/afollestad/materialdialogs/prefs/MaterialMultiSelectListPreference.java
package com.afollestad.materialdialogs.prefs; import android.annotation.TargetApi; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.preference.MultiSelectListPreference; import android.util.AttributeSet; import android.view.View; import com.afollestad.materialdialogs.MaterialDialog; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This class only works on Honeycomb (API 11) and above. * * @author Aidan Follestad (afollestad) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MaterialMultiSelectListPreference extends MultiSelectListPreference { private Context context; private MaterialDialog mDialog; public MaterialMultiSelectListPreference(Context context) { this(context, null); } public MaterialMultiSelectListPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context); } @Override public void setEntries(CharSequence[] entries) { super.setEntries(entries); if (mDialog != null) mDialog.setItems(entries); } private void init(Context context) { this.context = context; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) setWidgetLayoutResource(0); } @Override protected void showDialog(Bundle state) { List<Integer> indicies = new ArrayList<>(); for (String s : getValues()) indicies.add(findIndexOfValue(s)); MaterialDialog.Builder builder = new MaterialDialog.Builder(context) .title(getDialogTitle()) .content(getDialogMessage()) .icon(getDialogIcon()) .negativeText(getNegativeButtonText()) .positiveText(getPositiveButtonText()) .items(getEntries()) .itemsCallbackMultiChoice(indicies.toArray(new Integer[indicies.size()]), new MaterialDialog.ListCallbackMulti() { @Override public void onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) { onClick(null, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); final Set<String> values = new HashSet<>(); for (CharSequence s : text) values.add((String) s); if (callChangeListener(values)) setValues(values); } }) .dismissListener(this); final View contentView = onCreateDialogView(); if (contentView != null) { onBindDialogView(contentView); builder.customView(contentView, false); } else { builder.content(getDialogMessage()); } mDialog = builder.show(); } }
Update MaterialMultiSelectListPreference.java fix issue #339
library/src/main/java/com/afollestad/materialdialogs/prefs/MaterialMultiSelectListPreference.java
Update MaterialMultiSelectListPreference.java
<ide><path>ibrary/src/main/java/com/afollestad/materialdialogs/prefs/MaterialMultiSelectListPreference.java <ide> @Override <ide> protected void showDialog(Bundle state) { <ide> List<Integer> indicies = new ArrayList<>(); <del> for (String s : getValues()) <del> indicies.add(findIndexOfValue(s)); <add> for (String s : getValues()) { <add> int index = findIndexOfValue(s); <add> if(index >= 0) { <add> indicies.add(findIndexOfValue(s)); <add> } <add> } <ide> MaterialDialog.Builder builder = new MaterialDialog.Builder(context) <ide> .title(getDialogTitle()) <ide> .content(getDialogMessage())
Java
agpl-3.0
99ddadde4dc3f546dba66eb22d170ae0f2913973
0
rdkgit/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.netmgt.dao.hibernate; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.hibernate.HibernateException; import org.hibernate.Session; import org.opennms.netmgt.config.monitoringLocations.LocationDef; import org.opennms.netmgt.config.monitoringLocations.MonitoringLocationsConfiguration; import org.opennms.netmgt.dao.LocationMonitorDao; import org.opennms.netmgt.model.OnmsLocationMonitor; import org.opennms.netmgt.model.OnmsLocationSpecificStatus; import org.opennms.netmgt.model.OnmsMonitoredService; import org.opennms.netmgt.model.OnmsMonitoringLocationDefinition; import org.springframework.core.io.Resource; import org.springframework.orm.hibernate3.HibernateCallback; /** * @author <a href="mailto:[email protected]">David Hustace</a> * */ public class LocationMonitorDaoHibernate extends AbstractDaoHibernate<OnmsLocationMonitor, Integer> implements LocationMonitorDao { MonitoringLocationsConfiguration m_monitoringLocationsConfiguration; Resource m_monitoringLocationConfigResource; /** * Constructor that also initializes the required XML configurations * @throws IOException * @throws MarshalException * @throws ValidationException */ public LocationMonitorDaoHibernate() { super(OnmsLocationMonitor.class); if (m_monitoringLocationConfigResource != null) { initializeConfigurations(); } } @SuppressWarnings("unchecked") public List<OnmsMonitoringLocationDefinition> findAllMonitoringLocationDefinitions() { List<OnmsMonitoringLocationDefinition> onmsDefs = new ArrayList(); final List<LocationDef> locationDefCollection = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); if (locationDefCollection != null) { onmsDefs = convertDefs(locationDefCollection); } return onmsDefs; } private List<OnmsMonitoringLocationDefinition> convertDefs(List<LocationDef> defs) { List<OnmsMonitoringLocationDefinition> onmsDefs = new LinkedList<OnmsMonitoringLocationDefinition>(); for (LocationDef def : defs) { OnmsMonitoringLocationDefinition onmsDef = new OnmsMonitoringLocationDefinition(); onmsDef.setArea(def.getMonitoringArea()); onmsDef.setName(def.getLocationName()); onmsDef.setPollingPackageName(def.getPollingPackageName()); onmsDefs.add(onmsDef); } return onmsDefs; } /** * Don't call this for now. */ @SuppressWarnings("unchecked") public void saveMonitoringLocationDefinitions(Collection<OnmsMonitoringLocationDefinition> onmsDefs) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (OnmsMonitoringLocationDefinition onmsDef : onmsDefs) { for (LocationDef def : defs) { if (def.getLocationName().equals(onmsDef.getName())) { def.setMonitoringArea(onmsDef.getArea()); def.setPollingPackageName(onmsDef.getArea()); } } } saveMonitoringConfig(); } @SuppressWarnings("unchecked") public void saveMonitoringLocationDefinition(OnmsMonitoringLocationDefinition onmsDef) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (LocationDef def : defs) { if (onmsDef.getName().equals(def.getLocationName())) { def.setMonitoringArea(onmsDef.getArea()); def.setPollingPackageName(onmsDef.getPollingPackageName()); } } saveMonitoringConfig(); } //TODO: figure out way to synchronize this //TODO: write a castor template for the DAOs to use and do optimistic // locking. /** * @deprecated */ protected void saveMonitoringConfig() { String xml = null; StringWriter writer = new StringWriter(); try { Marshaller.marshal(m_monitoringLocationsConfiguration, writer); xml = writer.toString(); saveXml(xml); } catch (MarshalException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't marshal confg: \n"+ (xml != null ? xml : ""), e); } catch (ValidationException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't validate confg: \n"+ (xml != null ? xml : ""), e); } catch (IOException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't write confg: \n"+ (xml != null ? xml : ""), e); } } protected void saveXml(String xml) throws IOException { if (xml != null) { FileWriter fileWriter = new FileWriter(m_monitoringLocationConfigResource.getFile()); fileWriter.write(xml); fileWriter.flush(); fileWriter.close(); } } /** * * @param definitionName * @return */ @SuppressWarnings("unchecked") private LocationDef getLocationDef(final String definitionName) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); LocationDef matchingDef = null; for (LocationDef def : defs) { if (def.getLocationName().equals(definitionName)) { matchingDef = def; } } return matchingDef; } /** * Initializes all required XML configuration files * @throws MarshalException * @throws ValidationException * @throws IOException */ private void initializeConfigurations() { initializeMonitoringLocationDefinition(); } /** * Initializes the monitoring locations configuration file * @throws IOException * @throws MarshalException * @throws ValidationException */ private void initializeMonitoringLocationDefinition() { Reader rdr = null; try { rdr = new InputStreamReader(m_monitoringLocationConfigResource.getInputStream()); m_monitoringLocationsConfiguration = (MonitoringLocationsConfiguration) Unmarshaller.unmarshal(MonitoringLocationsConfiguration.class, rdr); } catch (IOException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } catch (MarshalException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } catch (ValidationException e) { throw new CastorObjectRetrievalFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } finally { try { if (rdr != null) rdr.close(); } catch (IOException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocatinDefintion: " + "Could not close XML stream", e); } } } protected class CastorObjectRetrievalFailureException extends org.springframework.orm.ObjectRetrievalFailureException { private static final long serialVersionUID = -5906087948002738350L; public CastorObjectRetrievalFailureException(String message, Throwable throwable) { super(message, throwable); } } protected class CastorDataAccessFailureException extends org.springframework.dao.DataAccessResourceFailureException { private static final long serialVersionUID = -5546624359373413751L; public CastorDataAccessFailureException(String message, Throwable throwable) { super(message, throwable); } } @SuppressWarnings("unchecked") public Collection<OnmsMonitoringLocationDefinition> findAllLocationDefinitions() { List<OnmsMonitoringLocationDefinition> eDefs = new LinkedList<OnmsMonitoringLocationDefinition>(); Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (LocationDef def : defs) { eDefs.add(createEntityDef(def)); } return eDefs; } private OnmsMonitoringLocationDefinition createEntityDef(LocationDef def) { OnmsMonitoringLocationDefinition eDef = new OnmsMonitoringLocationDefinition(); eDef.setArea(def.getMonitoringArea()); eDef.setName(def.getLocationName()); eDef.setPollingPackageName(def.getPollingPackageName()); return eDef; } public MonitoringLocationsConfiguration getMonitoringLocationsConfiguration() { return m_monitoringLocationsConfiguration; } public void setMonitoringLocationsConfiguration( MonitoringLocationsConfiguration monitoringLocationsConfiguration) { m_monitoringLocationsConfiguration = monitoringLocationsConfiguration; } public Resource getMonitoringLocationConfigResource() { return m_monitoringLocationConfigResource; } public void setMonitoringLocationConfigResource(Resource monitoringLocationResource) { m_monitoringLocationConfigResource = monitoringLocationResource; initializeMonitoringLocationDefinition(); } public OnmsMonitoringLocationDefinition findMonitoringLocationDefinition(String monitoringLocationDefinitionName) { return createEntityDef(getLocationDef(monitoringLocationDefinitionName)); } public OnmsLocationSpecificStatus getMostRecentStatusChange(final OnmsLocationMonitor locationMonitor, final OnmsMonitoredService monSvc) { HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { return session.createQuery("from OnmsLocationSpecificStatus status where status.locationMonitor = :locationMonitor and status.monitoredService = :monitoredService order by status.pollResult.timestamp desc") .setEntity("locationMonitor", locationMonitor) .setEntity("monitoredService", monSvc) .setMaxResults(1) .uniqueResult(); } }; return (OnmsLocationSpecificStatus)getHibernateTemplate().execute(callback); } public void saveStatusChange(OnmsLocationSpecificStatus statusChange) { getHibernateTemplate().save(statusChange); } public OnmsLocationMonitor findByLocationDefinition(OnmsMonitoringLocationDefinition locationDefinition) { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } public Collection<OnmsLocationSpecificStatus> getAllMostRecentStatusChanges() { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } public Collection<OnmsLocationSpecificStatus> getStatusChangesBetween(Date startDate, Date endDate) { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } }
opennms-dao/src/main/java/org/opennms/netmgt/dao/hibernate/LocationMonitorDaoHibernate.java
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.netmgt.dao.hibernate; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.hibernate.HibernateException; import org.hibernate.Session; import org.opennms.netmgt.config.monitoringLocations.LocationDef; import org.opennms.netmgt.config.monitoringLocations.MonitoringLocationsConfiguration; import org.opennms.netmgt.dao.LocationMonitorDao; import org.opennms.netmgt.model.OnmsLocationMonitor; import org.opennms.netmgt.model.OnmsLocationSpecificStatus; import org.opennms.netmgt.model.OnmsMonitoredService; import org.opennms.netmgt.model.OnmsMonitoringLocationDefinition; import org.springframework.core.io.Resource; import org.springframework.orm.hibernate3.HibernateCallback; /** * @author <a href="mailto:[email protected]">David Hustace</a> * */ public class LocationMonitorDaoHibernate extends AbstractDaoHibernate<OnmsLocationMonitor, Integer> implements LocationMonitorDao { MonitoringLocationsConfiguration m_monitoringLocationsConfiguration; Resource m_monitoringLocationConfigResource; /** * Constructor that also initializes the required XML configurations * @throws IOException * @throws MarshalException * @throws ValidationException */ public LocationMonitorDaoHibernate() { super(OnmsLocationMonitor.class); if (m_monitoringLocationConfigResource != null) { initializeConfigurations(); } } @SuppressWarnings("unchecked") public List<OnmsMonitoringLocationDefinition> findAllMonitoringLocationDefinitions() { List<OnmsMonitoringLocationDefinition> onmsDefs = new ArrayList(); final List<LocationDef> locationDefCollection = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); if (locationDefCollection != null) { onmsDefs = convertDefs(locationDefCollection); } return onmsDefs; } private List<OnmsMonitoringLocationDefinition> convertDefs(List<LocationDef> defs) { List<OnmsMonitoringLocationDefinition> onmsDefs = new LinkedList<OnmsMonitoringLocationDefinition>(); for (LocationDef def : defs) { OnmsMonitoringLocationDefinition onmsDef = new OnmsMonitoringLocationDefinition(); onmsDef.setArea(def.getMonitoringArea()); onmsDef.setName(def.getLocationName()); onmsDef.setPollingPackageName(def.getPollingPackageName()); onmsDefs.add(onmsDef); } return onmsDefs; } /** * Don't call this for now. */ @SuppressWarnings("unchecked") public void saveMonitoringLocationDefinitions(Collection<OnmsMonitoringLocationDefinition> onmsDefs) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (OnmsMonitoringLocationDefinition onmsDef : onmsDefs) { for (LocationDef def : defs) { if (def.getLocationName().equals(onmsDef.getName())) { def.setMonitoringArea(onmsDef.getArea()); def.setPollingPackageName(onmsDef.getArea()); } } } saveMonitoringConfig(); } @SuppressWarnings("unchecked") public void saveMonitoringLocationDefinition(OnmsMonitoringLocationDefinition onmsDef) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (LocationDef def : defs) { if (onmsDef.getName().equals(def.getLocationName())) { def.setMonitoringArea(onmsDef.getArea()); def.setPollingPackageName(onmsDef.getPollingPackageName()); } } saveMonitoringConfig(); } //TODO: figure out way to synchronize this //TODO: write a castor template for the DAOs to use and do optimistic // locking. /** * @deprecated */ protected void saveMonitoringConfig() { String xml = null; StringWriter writer = new StringWriter(); try { Marshaller.marshal(m_monitoringLocationsConfiguration, writer); xml = writer.toString(); saveXml(xml); } catch (MarshalException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't marshal confg: \n"+ (xml != null ? xml : ""), e); } catch (ValidationException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't validate confg: \n"+ (xml != null ? xml : ""), e); } catch (IOException e) { throw new CastorDataAccessFailureException("saveMonitoringConfig: couldn't write confg: \n"+ (xml != null ? xml : ""), e); } } protected void saveXml(String xml) throws IOException { if (xml != null) { FileWriter fileWriter = new FileWriter(m_monitoringLocationConfigResource.getFile()); fileWriter.write(xml); fileWriter.flush(); fileWriter.close(); } } /** * * @param definitionName * @return */ @SuppressWarnings("unchecked") private LocationDef getLocationDef(final String definitionName) { Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); LocationDef matchingDef = null; for (LocationDef def : defs) { if (def.getLocationName().equals(definitionName)) { matchingDef = def; } } return matchingDef; } /** * Initializes all required XML configuration files * @throws MarshalException * @throws ValidationException * @throws IOException */ private void initializeConfigurations() { initializeMonitoringLocationDefinition(); } /** * Initializes the monitoring locations configuration file * @throws IOException * @throws MarshalException * @throws ValidationException */ private void initializeMonitoringLocationDefinition() { Reader rdr = null; try { rdr = new InputStreamReader(m_monitoringLocationConfigResource.getInputStream()); m_monitoringLocationsConfiguration = (MonitoringLocationsConfiguration) Unmarshaller.unmarshal(MonitoringLocationsConfiguration.class, rdr); } catch (IOException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } catch (MarshalException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } catch (ValidationException e) { throw new CastorObjectRetrievalFailureException("initializeMonitoringLocationDefinition: " + "Could not marshal configuration", e); } finally { try { if (rdr != null) rdr.close(); } catch (IOException e) { throw new CastorDataAccessFailureException("initializeMonitoringLocatinDefintion: " + "Could not close XML stream", e); } } } protected class CastorObjectRetrievalFailureException extends org.springframework.orm.ObjectRetrievalFailureException { private static final long serialVersionUID = -5906087948002738350L; public CastorObjectRetrievalFailureException(String message, Throwable throwable) { super(message, throwable); } } protected class CastorDataAccessFailureException extends org.springframework.dao.DataAccessResourceFailureException { private static final long serialVersionUID = -5546624359373413751L; public CastorDataAccessFailureException(String message, Throwable throwable) { super(message, throwable); } } @SuppressWarnings("unchecked") public Collection<OnmsMonitoringLocationDefinition> findAllLocationDefinitions() { List<OnmsMonitoringLocationDefinition> eDefs = new LinkedList<OnmsMonitoringLocationDefinition>(); Collection<LocationDef> defs = m_monitoringLocationsConfiguration.getLocations().getLocationDefCollection(); for (LocationDef def : defs) { eDefs.add(createEntityDef(def)); } return eDefs; } private OnmsMonitoringLocationDefinition createEntityDef(LocationDef def) { OnmsMonitoringLocationDefinition eDef = new OnmsMonitoringLocationDefinition(); eDef.setArea(def.getMonitoringArea()); eDef.setName(def.getLocationName()); eDef.setPollingPackageName(def.getPollingPackageName()); return eDef; } public MonitoringLocationsConfiguration getMonitoringLocationsConfiguration() { return m_monitoringLocationsConfiguration; } public void setMonitoringLocationsConfiguration( MonitoringLocationsConfiguration monitoringLocationsConfiguration) { m_monitoringLocationsConfiguration = monitoringLocationsConfiguration; } public Resource getMonitoringLocationConfigResource() { return m_monitoringLocationConfigResource; } public void setMonitoringLocationConfigResource(Resource monitoringLocationResource) { m_monitoringLocationConfigResource = monitoringLocationResource; initializeMonitoringLocationDefinition(); } public OnmsMonitoringLocationDefinition findMonitoringLocationDefinition(String monitoringLocationDefinitionName) { return createEntityDef(getLocationDef(monitoringLocationDefinitionName)); } public OnmsLocationSpecificStatus getMostRecentStatusChange(final OnmsLocationMonitor locationMonitor, final OnmsMonitoredService monSvc) { HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { return session.createQuery("from OnmsLocationSpecificStatus status where status.locationMonitor = :locationMonitor and status.monitoredService = :monitoredService order by status.pollResult.timestamp") .setEntity("locationMonitor", locationMonitor) .setEntity("monitoredService", monSvc) .setMaxResults(1) .uniqueResult(); } }; return (OnmsLocationSpecificStatus)getHibernateTemplate().execute(callback); } public void saveStatusChange(OnmsLocationSpecificStatus statusChange) { getHibernateTemplate().save(statusChange); } public OnmsLocationMonitor findByLocationDefinition(OnmsMonitoringLocationDefinition locationDefinition) { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } public Collection<OnmsLocationSpecificStatus> getAllMostRecentStatusChanges() { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } public Collection<OnmsLocationSpecificStatus> getStatusChangesBetween(Date startDate, Date endDate) { // XXX brozow/drv4doe: write this part. :-) throw new IllegalArgumentException("This method hasn't yet been implemented"); } }
fix return of most recent rather then earlist
opennms-dao/src/main/java/org/opennms/netmgt/dao/hibernate/LocationMonitorDaoHibernate.java
fix return of most recent rather then earlist
<ide><path>pennms-dao/src/main/java/org/opennms/netmgt/dao/hibernate/LocationMonitorDaoHibernate.java <ide> <ide> public Object doInHibernate(Session session) <ide> throws HibernateException, SQLException { <del> return session.createQuery("from OnmsLocationSpecificStatus status where status.locationMonitor = :locationMonitor and status.monitoredService = :monitoredService order by status.pollResult.timestamp") <add> return session.createQuery("from OnmsLocationSpecificStatus status where status.locationMonitor = :locationMonitor and status.monitoredService = :monitoredService order by status.pollResult.timestamp desc") <ide> .setEntity("locationMonitor", locationMonitor) <ide> .setEntity("monitoredService", monSvc) <ide> .setMaxResults(1)
Java
bsd-3-clause
15c293ea89dcd811962889dd540d4bacde58b70c
0
dougqh/JAK
package net.dougqh.jak.disassembler; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import net.dougqh.jak.Jak; import net.dougqh.jak.JavaField; import net.dougqh.jak.JavaMethodDescriptor; import net.dougqh.java.meta.types.JavaTypes; import static net.dougqh.jak.jvm.ConstantPoolConstants.*; /** * Implementation of ConstantPool used during reading of class files. */ final class ConstantPool { public static final class MethodTypeDescriptor { final List<Type> paramTypes; final Type returnType; MethodTypeDescriptor( final List<Type> paramTypes, final Type returnType ) { this.paramTypes = paramTypes; this.returnType = returnType; } } /* This class uses a rather intricate multi-level caching scheme to handle decoding UTF-8 strings into objects. When a UTF-8 is decoded indirectly through a singular or dual reference, the decoded value is stored inside the reference object and is assumed to be correct going forward. Conversely, when a UTF-8 is decoded directly (not through a reference - as is the case for fields and methods being declared), the decoded value is cached, but the decoder must be checked for each request. The difference is that when coming through a reference, the type of the decoder can be assumed to be constant. So by caching the value in the reference directly, the interpretation is known to always be correct in that context. However, when decoding directly, the UTF-8 reference could be shared by a string literal and the value being decoded. While this is highly unlikely, ConstantPool checks for this case anyway to guarantee correctness. */ private final Object[] constants; private final DecodeCacheEntry[] decodeCache; ConstantPool( final JvmInputStream in ) throws IOException { int count = in.u2(); this.constants = new Object[count]; this.decodeCache = new DecodeCacheEntry[count]; for ( int index = 1; index < count; ++index ) { byte tag = in.u1(); switch ( tag ) { case CLASS: { this.constants[index] = readClassInfo(in); break; } case FIELD_REF: { this.constants[index] = readFieldRef(in); break; } case METHOD_REF: { this.constants[index] = readMethodRef(in); break; } case INTERFACE_METHOD_REF: { this.constants[index] = readInterfaceMethodRef(in); break; } case STRING: { this.constants[index] = readString(in); break; } case INTEGER: { this.constants[index] = readInteger(in); break; } case FLOAT: { this.constants[index] = readFloat(in); break; } case LONG: { this.constants[index] = readLong(in); ++index; break; } case DOUBLE: { this.constants[index] = readDouble(in); ++index; break; } case NAME_AND_TYPE: { this.constants[index] = readNameAndType(in); break; } case UTF8: { this.constants[index] = readUtf8(in); break; } } } } public final String typeName( final int classIndex ) { int stringIndex = this.index(classIndex); return translateClass( this.utf8(stringIndex) ); } public final Type type( final int classIndex ) { return this.decodeRef( classIndex, TypeDecoder.INSTANCE ); } public final int intValue( final int index ) { return (Integer)this.constants[index]; } public final float floatValue( final int index ) { return (Float)this.constants[index]; } public final long longValue( final int index ) { return (Long)this.constants[index]; } public final double doubleValue( final int index ) { return (Double)this.constants[index]; } public final String utf8( final int index ) { return (String)this.constants[index]; } public final Type targetType( final int refIndex ) { return this.type( this.firstIndex(refIndex) ); } public final JavaField field( final int refIndex ) { int nameAndTypeIndex = this.secondIndex(refIndex); String name = this.decodeFirstRef(nameAndTypeIndex, StringDecoder.INSTANCE); Type type = this.decodeSecondRef(nameAndTypeIndex, FieldDescriptorDecoder.INSTANCE); return Jak.field(type, name); } public final MethodTypeDescriptor methodTypeDescriptor( final int index ) { return this.decode(index, MethodSignatureDecoder.INSTANCE); } public final JavaMethodDescriptor methodRef( final int refIndex ) { int nameAndTypeIndex = this.secondIndex(refIndex); String name = this.decodeFirstRef(nameAndTypeIndex, StringDecoder.INSTANCE); MethodTypeDescriptor signature = this.decodeSecondRef(nameAndTypeIndex, MethodSignatureDecoder.INSTANCE); return Jak.method(signature.returnType, name, signature.paramTypes); } private final int index( final int index ) { return ( (SingularReference)this.constants[index] ).index; } private final <T> T decode( final int index, final Decoder<T> decoder ) { DecodeCacheEntry cacheEntry = this.decodeCache[index]; if ( cacheEntry != null && cacheEntry.matches(decoder) ) { return cacheEntry.<T>get(); } String string = this.utf8(index); T value = decoder.decode(string); this.decodeCache[index] = new DecodeCacheEntry(decoder, value); return value; } private final <T> T decodeRef( final int index, final Decoder<T> decoder ) { SingularReference ref = (SingularReference)this.constants[index]; if ( ref.decoded == null ) { String utf8 = this.utf8(ref.index); ref.decoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.decoded; return (T)result; } private final int firstIndex( final int index ) { return ( (DualReference)this.constants[index] ).firstIndex; } private final <T> T decodeFirstRef( final int index, final Decoder<T> decoder ) { DualReference ref = (DualReference)this.constants[index]; if ( ref.firstDecoded == null ) { String utf8 = this.utf8(ref.firstIndex); ref.firstDecoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.firstDecoded; return (T)result; } private final int secondIndex( final int index ) { return ( (DualReference)this.constants[index] ).secondIndex; } private final <T> T decodeSecondRef( final int index, final Decoder<T> decoder ) { DualReference ref = (DualReference)this.constants[index]; if ( ref.secondDecoded == null ) { String utf8 = this.utf8(ref.secondIndex); ref.secondDecoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.secondDecoded; return (T)result; } private static final SingularReference readClassInfo( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); return new SingularReference( classIndex ); } private static final DualReference readFieldRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference(classIndex, nameAndTypeIndex); } private static final DualReference readMethodRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference(classIndex, nameAndTypeIndex); } private static final DualReference readInterfaceMethodRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference( classIndex, nameAndTypeIndex ); } private static final SingularReference readString( final JvmInputStream in ) throws IOException { int utf8Index = in.u2(); return new SingularReference(utf8Index); } private static final Integer readInteger( final JvmInputStream in ) throws IOException { return in.u4(); } private static final Float readFloat( final JvmInputStream in ) throws IOException { return in.u4Float(); } private final Long readLong( final JvmInputStream in ) throws IOException { return in.u8(); } private static final Double readDouble( final JvmInputStream in ) throws IOException { return in.u8Double(); } private static final DualReference readNameAndType( final JvmInputStream in ) throws IOException { int nameIndex = in.u2(); int descriptorIndex = in.u2(); return new DualReference(nameIndex, descriptorIndex); } private static final String readUtf8( final JvmInputStream in ) throws IOException { int length = in.u2(); return in.utf8(length); } private static final String translateClass(final String jvmClassName) { return jvmClassName.replace( '/', '.' ); } /** * Used for any single reference entry - like class entry */ static final class SingularReference { final int index; Object decoded; SingularReference( final int index ) { this.index = index; } } /** * Used for any dual reference entry - like... * - method ref * - interface method ref * - field ref * - name and type pair */ static final class DualReference { final int firstIndex; final int secondIndex; Object firstDecoded; Object secondDecoded; DualReference( final int firstIndex, final int secondIndex ) { this.firstIndex = firstIndex; this.secondIndex = secondIndex; } } static abstract class Decoder<T> { abstract T decode(final String value); } static final class StringDecoder extends Decoder<String> { static final StringDecoder INSTANCE = new StringDecoder(); private StringDecoder() {} @Override final String decode( final String value ) { return value; } } static final class TypeDecoder extends Decoder<Type> { static final TypeDecoder INSTANCE = new TypeDecoder(); private TypeDecoder() {} @Override final Type decode( final String value ) { // Not worried about primitives, so I can user a lighter implementation return JavaTypes.objectTypeName( translateClass(value) ); } } static final class FieldDescriptorDecoder extends Decoder<Type> { static final FieldDescriptorDecoder INSTANCE = new FieldDescriptorDecoder(); private FieldDescriptorDecoder() {} @Override final Type decode( final String value ) { return JavaTypes.fromPersistedName(value); } } static final class MethodSignatureDecoder extends Decoder<MethodTypeDescriptor> { static final MethodSignatureDecoder INSTANCE = new MethodSignatureDecoder(); private MethodSignatureDecoder() {} @Override final MethodTypeDescriptor decode( final String signature ) { if ( signature.startsWith( "()" ) ) { return handleWithoutParameters(signature); } else { return handleWithParameters(signature); } } private static final MethodTypeDescriptor handleWithoutParameters( final String signature ) { String returnTypeRemainder = signature.substring(2); return new MethodTypeDescriptor( Collections.<Type>emptyList(), JavaTypes.fromPersistedName(returnTypeRemainder)); } private static final MethodTypeDescriptor handleWithParameters( final String signature ) { throw new IllegalStateException("not implemented"); } } private static final class DecodeCacheEntry { private final Decoder<?> decoder; private final Object value; public DecodeCacheEntry(final Decoder<?> decoder, final Object value) { this.decoder = decoder; this.value = value; } boolean matches(final Decoder<?> decoder) { return this.decoder.equals(decoder); } <T> T get() { @SuppressWarnings("unchecked") T result = (T)value; return result; } } }
net.dougqh.jak.jvm.disassembler/src/net/dougqh/jak/disassembler/ConstantPool.java
package net.dougqh.jak.disassembler; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import net.dougqh.jak.Jak; import net.dougqh.jak.JavaField; import net.dougqh.jak.JavaMethodDescriptor; import net.dougqh.java.meta.types.JavaTypes; import static net.dougqh.jak.jvm.ConstantPoolConstants.*; /** * Implementation of ConstantPool used during reading of class files. */ final class ConstantPool { public static final class MethodTypeDescriptor { final List<Type> paramTypes; final Type returnType; MethodTypeDescriptor( final List<Type> paramTypes, final Type returnType ) { this.paramTypes = paramTypes; this.returnType = returnType; } } /* This class uses a rather intricate multi-level caching scheme to handle decoding UTF-8 strings into objects. When a UTF-8 is decoded indirectly through a singular or dual reference, the decoded value is stored inside the reference object and is assumed to be correct going forward. Conversely, when a UTF-8 is decoded directly (not through a reference - as is the case for fields and methods being declared), the decoded value is cached, but the decoder must be checked for each request. The difference is that when coming through a reference, the type of the decoder can be assumed to be constant. So by caching the value in the reference directly, the interpretation is known to always be correct in that context. However, when decoding directly, the UTF-8 reference could be shared by a string literal and the value being decoded. While this is highly unlikely, ConstantPool checks for this case anyway to guarantee correctness. */ private final Object[] constants; private final DecodeCacheEntry[] decodeCache; ConstantPool( final JvmInputStream in ) throws IOException { int count = in.u2(); this.constants = new Object[ count ]; this.decodeCache = new DecodeCacheEntry[ count ]; for ( int index = 1; index < count; ++index ) { byte tag = in.u1(); switch ( tag ) { case CLASS: { this.constants[ index ] = readClassInfo( in ); break; } case FIELD_REF: { this.constants[ index ] = readFieldRef( in ); break; } case METHOD_REF: { this.constants[ index ] = readMethodRef( in ); break; } case INTERFACE_METHOD_REF: { this.constants[ index ] = readInterfaceMethodRef( in ); break; } case STRING: { this.constants[ index ] = readString( in ); break; } case INTEGER: { this.constants[ index ] = readInteger( in ); break; } case FLOAT: { this.constants[ index ] = readFloat( in ); break; } case LONG: { this.constants[ index ] = readLong( in ); ++index; break; } case DOUBLE: { this.constants[ index ] = readDouble( in ); ++index; break; } case NAME_AND_TYPE: { this.constants[ index ] = readNameAndType( in ); break; } case UTF8: { this.constants[ index ] = readUtf8( in ); break; } } } } public final String typeName( final int classIndex ) { int stringIndex = this.index( classIndex ); return translateClass( this.utf8( stringIndex ) ); } public final Type type( final int classIndex ) { return this.decodeRef( classIndex, TypeDecoder.INSTANCE ); } public final int intValue( final int index ) { return (Integer)this.constants[ index ]; } public final float floatValue( final int index ) { return (Float)this.constants[ index ]; } public final long longValue( final int index ) { return (Long)this.constants[ index ]; } public final double doubleValue( final int index ) { return (Double)this.constants[ index ]; } public final String utf8( final int index ) { return (String)this.constants[ index ]; } public final Type targetType( final int refIndex ) { return this.type( this.firstIndex( refIndex ) ); } public final JavaField field( final int refIndex ) { int nameAndTypeIndex = this.secondIndex(refIndex); String name = this.decodeFirstRef(nameAndTypeIndex, StringDecoder.INSTANCE); Type type = this.decodeSecondRef(nameAndTypeIndex, FieldDescriptorDecoder.INSTANCE); return Jak.field(type, name); } public final MethodTypeDescriptor methodTypeDescriptor( final int index ) { return this.decode(index, MethodSignatureDecoder.INSTANCE); } public final JavaMethodDescriptor methodRef( final int refIndex ) { int nameAndTypeIndex = this.secondIndex(refIndex); String name = this.decodeFirstRef(nameAndTypeIndex, StringDecoder.INSTANCE); MethodTypeDescriptor signature = this.decodeSecondRef(nameAndTypeIndex, MethodSignatureDecoder.INSTANCE); return Jak.method(signature.returnType, name, signature.paramTypes); } private final int index( final int index ) { return ( (SingularReference)this.constants[ index ] ).index; } private final <T> T decode( final int index, final Decoder<T> decoder ) { DecodeCacheEntry cacheEntry = this.decodeCache[index]; if ( cacheEntry != null && cacheEntry.matches(decoder) ) { return cacheEntry.<T>get(); } String string = this.utf8(index); T value = decoder.decode(string); this.decodeCache[index] = new DecodeCacheEntry(decoder, value); return value; } private final <T> T decodeRef( final int index, final Decoder<T> decoder ) { SingularReference ref = (SingularReference)this.constants[index]; if ( ref.decoded == null ) { String utf8 = this.utf8(ref.index); ref.decoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.decoded; return (T)result; } private final int firstIndex( final int index ) { return ( (DualReference)this.constants[ index ] ).firstIndex; } private final <T> T decodeFirstRef( final int index, final Decoder<T> decoder ) { DualReference ref = (DualReference)this.constants[index]; if ( ref.firstDecoded == null ) { String utf8 = this.utf8(ref.firstIndex); ref.firstDecoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.firstDecoded; return (T)result; } private final int secondIndex( final int index ) { return ( (DualReference)this.constants[ index ] ).secondIndex; } private final <T> T decodeSecondRef( final int index, final Decoder<T> decoder ) { DualReference ref = (DualReference)this.constants[ index ]; if ( ref.secondDecoded == null ) { String utf8 = this.utf8(ref.secondIndex); ref.secondDecoded = decoder.decode(utf8); } @SuppressWarnings("unchecked") T result = (T)ref.secondDecoded; return (T)result; } private static final SingularReference readClassInfo( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); return new SingularReference( classIndex ); } private static final DualReference readFieldRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference( classIndex, nameAndTypeIndex ); } private static final DualReference readMethodRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference( classIndex, nameAndTypeIndex ); } private static final DualReference readInterfaceMethodRef( final JvmInputStream in ) throws IOException { int classIndex = in.u2(); int nameAndTypeIndex = in.u2(); return new DualReference( classIndex, nameAndTypeIndex ); } private static final SingularReference readString( final JvmInputStream in ) throws IOException { int utf8Index = in.u2(); return new SingularReference( utf8Index ); } private static final Integer readInteger( final JvmInputStream in ) throws IOException { return in.u4(); } private static final Float readFloat( final JvmInputStream in ) throws IOException { return in.u4Float(); } private final Long readLong( final JvmInputStream in ) throws IOException { return in.u8(); } private static final Double readDouble( final JvmInputStream in ) throws IOException { return in.u8Double(); } private static final DualReference readNameAndType( final JvmInputStream in ) throws IOException { int nameIndex = in.u2(); int descriptorIndex = in.u2(); return new DualReference( nameIndex, descriptorIndex ); } private static final String readUtf8( final JvmInputStream in ) throws IOException { int length = in.u2(); return in.utf8( length ); } private static final String translateClass(final String jvmClassName) { return jvmClassName.replace( '/', '.' ); } /** * Used for any single reference entry - like class entry */ static final class SingularReference { final int index; Object decoded; SingularReference( final int index ) { this.index = index; } } /** * Used for any dual reference entry - like... * - method ref * - interface method ref * - field ref * - name and type pair */ static final class DualReference { final int firstIndex; final int secondIndex; Object firstDecoded; Object secondDecoded; DualReference( final int firstIndex, final int secondIndex ) { this.firstIndex = firstIndex; this.secondIndex = secondIndex; } } static abstract class Decoder<T> { abstract T decode(final String value); } static final class StringDecoder extends Decoder<String> { static final StringDecoder INSTANCE = new StringDecoder(); private StringDecoder() {} @Override final String decode( final String value ) { return value; } } static final class TypeDecoder extends Decoder<Type> { static final TypeDecoder INSTANCE = new TypeDecoder(); private TypeDecoder() {} @Override final Type decode( final String value ) { // Not worried about primitives, so I can user a lighter implementation return JavaTypes.objectTypeName( translateClass( value ) ); } } static final class FieldDescriptorDecoder extends Decoder<Type> { static final FieldDescriptorDecoder INSTANCE = new FieldDescriptorDecoder(); private FieldDescriptorDecoder() {} @Override final Type decode( final String value ) { return JavaTypes.fromPersistedName( value ); } } static final class MethodSignatureDecoder extends Decoder<MethodTypeDescriptor> { static final MethodSignatureDecoder INSTANCE = new MethodSignatureDecoder(); private MethodSignatureDecoder() {} @Override final MethodTypeDescriptor decode( final String signature ) { if ( signature.startsWith( "()" ) ) { return handleWithoutParameters( signature ); } else { return handleWithParameters( signature ); } } private static final MethodTypeDescriptor handleWithoutParameters( final String signature ) { String returnTypeRemainder = signature.substring(2); return new MethodTypeDescriptor( Collections.<Type>emptyList(), JavaTypes.fromPersistedName(returnTypeRemainder)); } private static final MethodTypeDescriptor handleWithParameters( final String signature ) { throw new IllegalStateException("not implemented"); } } private static final class DecodeCacheEntry { private final Decoder<?> decoder; private final Object value; public DecodeCacheEntry(final Decoder<?> decoder, final Object value) { this.decoder = decoder; this.value = value; } boolean matches(final Decoder<?> decoder) { return this.decoder.equals(decoder); } <T> T get() { @SuppressWarnings("unchecked") T result = (T)value; return result; } } }
De-spacing
net.dougqh.jak.jvm.disassembler/src/net/dougqh/jak/disassembler/ConstantPool.java
De-spacing
<ide><path>et.dougqh.jak.jvm.disassembler/src/net/dougqh/jak/disassembler/ConstantPool.java <ide> <ide> ConstantPool( final JvmInputStream in ) throws IOException { <ide> int count = in.u2(); <del> this.constants = new Object[ count ]; <del> this.decodeCache = new DecodeCacheEntry[ count ]; <add> this.constants = new Object[count]; <add> this.decodeCache = new DecodeCacheEntry[count]; <ide> <ide> for ( int index = 1; index < count; ++index ) { <ide> byte tag = in.u1(); <ide> <ide> switch ( tag ) { <ide> case CLASS: { <del> this.constants[ index ] = readClassInfo( in ); <add> this.constants[index] = readClassInfo(in); <ide> break; <ide> } <ide> <ide> case FIELD_REF: { <del> this.constants[ index ] = readFieldRef( in ); <add> this.constants[index] = readFieldRef(in); <ide> break; <ide> } <ide> <ide> case METHOD_REF: { <del> this.constants[ index ] = readMethodRef( in ); <add> this.constants[index] = readMethodRef(in); <ide> break; <ide> } <ide> <ide> case INTERFACE_METHOD_REF: { <del> this.constants[ index ] = readInterfaceMethodRef( in ); <add> this.constants[index] = readInterfaceMethodRef(in); <ide> break; <ide> } <ide> <ide> case STRING: { <del> this.constants[ index ] = readString( in ); <add> this.constants[index] = readString(in); <ide> break; <ide> } <ide> <ide> case INTEGER: { <del> this.constants[ index ] = readInteger( in ); <add> this.constants[index] = readInteger(in); <ide> break; <ide> } <ide> <ide> case FLOAT: { <del> this.constants[ index ] = readFloat( in ); <add> this.constants[index] = readFloat(in); <ide> break; <ide> } <ide> <ide> case LONG: { <del> this.constants[ index ] = readLong( in ); <add> this.constants[index] = readLong(in); <ide> ++index; <ide> break; <ide> } <ide> <ide> case DOUBLE: { <del> this.constants[ index ] = readDouble( in ); <add> this.constants[index] = readDouble(in); <ide> ++index; <ide> break; <ide> } <ide> <ide> case NAME_AND_TYPE: { <del> this.constants[ index ] = readNameAndType( in ); <add> this.constants[index] = readNameAndType(in); <ide> break; <ide> } <ide> <ide> case UTF8: { <del> this.constants[ index ] = readUtf8( in ); <add> this.constants[index] = readUtf8(in); <ide> break; <ide> } <ide> } <ide> } <ide> <ide> public final String typeName( final int classIndex ) { <del> int stringIndex = this.index( classIndex ); <del> <del> return translateClass( this.utf8( stringIndex ) ); <add> int stringIndex = this.index(classIndex); <add> <add> return translateClass( this.utf8(stringIndex) ); <ide> } <ide> <ide> public final Type type( final int classIndex ) { <ide> } <ide> <ide> public final int intValue( final int index ) { <del> return (Integer)this.constants[ index ]; <add> return (Integer)this.constants[index]; <ide> } <ide> <ide> public final float floatValue( final int index ) { <del> return (Float)this.constants[ index ]; <add> return (Float)this.constants[index]; <ide> } <ide> <ide> public final long longValue( final int index ) { <del> return (Long)this.constants[ index ]; <add> return (Long)this.constants[index]; <ide> } <ide> <ide> public final double doubleValue( final int index ) { <del> return (Double)this.constants[ index ]; <add> return (Double)this.constants[index]; <ide> } <ide> <ide> public final String utf8( final int index ) { <del> return (String)this.constants[ index ]; <add> return (String)this.constants[index]; <ide> } <ide> <ide> public final Type targetType( final int refIndex ) { <del> return this.type( this.firstIndex( refIndex ) ); <add> return this.type( this.firstIndex(refIndex) ); <ide> } <ide> <ide> public final JavaField field( final int refIndex ) { <ide> } <ide> <ide> private final int index( final int index ) { <del> return ( (SingularReference)this.constants[ index ] ).index; <add> return ( (SingularReference)this.constants[index] ).index; <ide> } <ide> <ide> private final <T> T decode( final int index, final Decoder<T> decoder ) { <ide> } <ide> <ide> private final int firstIndex( final int index ) { <del> return ( (DualReference)this.constants[ index ] ).firstIndex; <add> return ( (DualReference)this.constants[index] ).firstIndex; <ide> } <ide> <ide> private final <T> T decodeFirstRef( final int index, final Decoder<T> decoder ) { <ide> } <ide> <ide> private final int secondIndex( final int index ) { <del> return ( (DualReference)this.constants[ index ] ).secondIndex; <add> return ( (DualReference)this.constants[index] ).secondIndex; <ide> } <ide> <ide> private final <T> T decodeSecondRef( final int index, final Decoder<T> decoder ) { <del> DualReference ref = (DualReference)this.constants[ index ]; <add> DualReference ref = (DualReference)this.constants[index]; <ide> <ide> if ( ref.secondDecoded == null ) { <ide> String utf8 = this.utf8(ref.secondIndex); <ide> private static final DualReference readFieldRef( final JvmInputStream in ) throws IOException { <ide> int classIndex = in.u2(); <ide> int nameAndTypeIndex = in.u2(); <del> return new DualReference( classIndex, nameAndTypeIndex ); <add> return new DualReference(classIndex, nameAndTypeIndex); <ide> } <ide> <ide> private static final DualReference readMethodRef( final JvmInputStream in ) throws IOException { <ide> int classIndex = in.u2(); <ide> int nameAndTypeIndex = in.u2(); <del> return new DualReference( classIndex, nameAndTypeIndex ); <add> return new DualReference(classIndex, nameAndTypeIndex); <ide> } <ide> <ide> private static final DualReference readInterfaceMethodRef( final JvmInputStream in ) throws IOException { <ide> <ide> private static final SingularReference readString( final JvmInputStream in ) throws IOException { <ide> int utf8Index = in.u2(); <del> return new SingularReference( utf8Index ); <add> return new SingularReference(utf8Index); <ide> } <ide> <ide> private static final Integer readInteger( final JvmInputStream in ) throws IOException { <ide> int nameIndex = in.u2(); <ide> int descriptorIndex = in.u2(); <ide> <del> return new DualReference( nameIndex, descriptorIndex ); <add> return new DualReference(nameIndex, descriptorIndex); <ide> } <ide> <ide> private static final String readUtf8( final JvmInputStream in ) throws IOException { <ide> int length = in.u2(); <ide> <del> return in.utf8( length ); <add> return in.utf8(length); <ide> } <ide> <ide> private static final String translateClass(final String jvmClassName) { <ide> @Override <ide> final Type decode( final String value ) { <ide> // Not worried about primitives, so I can user a lighter implementation <del> return JavaTypes.objectTypeName( translateClass( value ) ); <add> return JavaTypes.objectTypeName( translateClass(value) ); <ide> } <ide> } <ide> <ide> <ide> @Override <ide> final Type decode( final String value ) { <del> return JavaTypes.fromPersistedName( value ); <add> return JavaTypes.fromPersistedName(value); <ide> } <ide> } <ide> <ide> @Override <ide> final MethodTypeDescriptor decode( final String signature ) { <ide> if ( signature.startsWith( "()" ) ) { <del> return handleWithoutParameters( signature ); <add> return handleWithoutParameters(signature); <ide> } else { <del> return handleWithParameters( signature ); <add> return handleWithParameters(signature); <ide> } <ide> } <ide>
Java
apache-2.0
d0ff33a67f6393e4d50d82c5f4db8506a622bd47
0
adrie4mac/commons-codec,apache/commons-codec,apache/commons-codec,mohanaraosv/commons-codec,mohanaraosv/commons-codec,mohanaraosv/commons-codec,adrie4mac/commons-codec,adrie4mac/commons-codec,apache/commons-codec
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Provides Base64 encoding and decoding in a streaming fashion (unlimited size). * When encoding the default lineLength is 76 characters and the default * lineEnding is CRLF, but these can be overridden by using the appropriate * constructor. * <p> * The default behaviour of the Base64InputStream is to DECODE, whereas the * default behaviour of the Base64OutputStream is to ENCODE, but this * behaviour can be overridden by using a different constructor. * </p><p> * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. * </p> * * @author Apache Software Foundation * @version $Id $ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @since 1.0-dev */ public class Base64InputStream extends FilterInputStream { private final boolean doEncode; private final Base64 base64; private final byte[] singleByte = new byte[1]; /** * Creates a Base64InputStream such that all data read is Base64-decoded * from the original provided InputStream. * * @param in InputStream to wrap. */ public Base64InputStream(InputStream in) { this(in, false); } /** * Creates a Base64InputStream such that all data read is either * Base64-encoded or Base64-decoded from the original provided InputStream. * * @param in InputStream to wrap. * @param doEncode true if we should encode all data read from us, * false if we should decode. */ public Base64InputStream(InputStream in, boolean doEncode) { super(in); this.doEncode = doEncode; this.base64 = new Base64(); } /** * Creates a Base64InputStream such that all data read is either * Base64-encoded or Base64-decoded from the original provided InputStream. * * @param in InputStream to wrap. * @param doEncode true if we should encode all data read from us, * false if we should decode. * @param lineLength If doEncode is true, each line of encoded * data will contain lineLength characters. If * doEncode is false, lineLength is ignored. * @param lineSeparator If doEncode is true, each line of encoded * data will be terminated with this byte sequence * (e.g. \r\n). If doEncode is false lineSeparator * is ignored. */ public Base64InputStream(InputStream in, boolean doEncode, int lineLength, byte[] lineSeparator) { super(in); this.doEncode = doEncode; this.base64 = new Base64(lineLength, lineSeparator); } /** * Reads one <code>byte</code> from this input stream. * Returns -1 if EOF has been reached. */ public int read() throws IOException { int r = read(singleByte, 0, 1); while (r == 0) { r = read(singleByte, 0, 1); } if (r > 0) { return singleByte[0] < 0 ? 256 + singleByte[0] : singleByte[0]; } else { return -1; } } /** * Attempts to read <code>len</code> bytes into the specified * <code>b</code> array starting at <code>offset</code> from * this InputStream. * * @throws IOException if an I/O error occurs. */ public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0 || offset + len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); // A little optimization to avoid System.arraycopy() // when possible. if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } return base64.readResults(b, offset, len); } } /** * {@inheritDoc} * @return false */ public boolean markSupported() { return false; // not an easy job to support marks } }
src/java/org/apache/commons/codec/binary/Base64InputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Provides Base64 encoding and decoding in a streaming fashion (unlimited size). * When encoding the default lineLength is 76 characters and the default * lineEnding is CRLF, but these can be overridden by using the appropriate * constructor. * <p> * The default behaviour of the Base64InputStream is to DECODE, whereas the * default behaviour of the Base64OutputStream is to ENCODE, but this * behaviour can be overridden by using a different constructor. * </p><p> * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. * </p> * * @author Apache Software Foundation * @version $Id $ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @since 1.0-dev */ public class Base64InputStream extends FilterInputStream { private final boolean doEncode; private final Base64 base64; private final byte[] singleByte = new byte[1]; /** * Creates a Base64InputStream such that all data read is Base64-decoded * from the original provided InputStream. * * @param in InputStream to wrap. */ public Base64InputStream(InputStream in) { this(in, false); } /** * Creates a Base64InputStream such that all data read is either * Base64-encoded or Base64-decoded from the original provided InputStream. * * @param in InputStream to wrap. * @param doEncode true if we should encode all data read from us, * false if we should decode. */ public Base64InputStream(InputStream in, boolean doEncode) { super(in); this.doEncode = doEncode; this.base64 = new Base64(); } /** * Creates a Base64InputStream such that all data read is either * Base64-encoded or Base64-decoded from the original provided InputStream. * * @param in InputStream to wrap. * @param doEncode true if we should encode all data read from us, * false if we should decode. * @param lineLength If doEncode is true, each line of encoded * data will contain lineLength characters. If * doEncode is false, lineLength is ignored. * @param lineSeparator If doEncode is true, each line of encoded * data will be terminated with this byte sequence * (e.g. \r\n). If doEncode is false lineSeparator * is ignored. */ public Base64InputStream(InputStream in, boolean doEncode, int lineLength, byte[] lineSeparator) { super(in); this.doEncode = doEncode; this.base64 = new Base64(lineLength, lineSeparator); } /** * Reads one <code>byte</code> from this input stream. * Returns -1 if EOF has been reached. */ public int read() throws IOException { int r = read(singleByte, 0, 1); while (r == 0) { r = read(singleByte, 0, 1); } if (r > 0) { return singleByte[0] < 0 ? 256 + singleByte[0] : singleByte[0]; } else { return -1; } } /** * Attempts to read <code>len</code> bytes into the specified * <code>b</code> array starting at <code>offset</code> from * this InputStream. * * @throws IOException if an I/O error occurs. */ public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0 || offset + len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); // A little optimization to avoid System.arraycopy() // when possible. if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } return base64.readResults(b, offset, len); } } }
We don't (yet) support marking the Base64 stream git-svn-id: cde5a1597f50f50feab6f72941f6b219c34291a1@669993 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/codec/binary/Base64InputStream.java
We don't (yet) support marking the Base64 stream
<ide><path>rc/java/org/apache/commons/codec/binary/Base64InputStream.java <ide> } <ide> } <ide> <del> <add> /** <add> * {@inheritDoc} <add> * @return false <add> */ <add> public boolean markSupported() { <add> return false; // not an easy job to support marks <add> } <ide> }
JavaScript
apache-2.0
400f2892bb6b897dc15351a99cbfbda72386ed78
0
c3nav/c3nav,c3nav/c3nav,c3nav/c3nav,c3nav/c3nav
(function () { /* * Workaround for 1px lines appearing in some browsers due to fractional transforms * and resulting anti-aliasing. * https://github.com/Leaflet/Leaflet/issues/3575 */ var originalInitTile = L.GridLayer.prototype._initTile; L.GridLayer.include({ _initTile: function (tile) { originalInitTile.call(this, tile); var tileSize = this.getTileSize(); tile.style.width = tileSize.x + 1 + 'px'; tile.style.height = tileSize.y + 1 + 'px'; } }); /* * Fix scroll wheel zoom on precise scrolling devices */ var originalPerformZoom = L.Map.ScrollWheelZoom.prototype._performZoom; L.Map.ScrollWheelZoom.include({ _performZoom: function () { if (this._delta) this._delta = (this._delta > 0) ? Math.max(this._delta, 60) : Math.min(this._delta, -60); originalPerformZoom.call(this); } }); }()); c3nav = { init: function () { c3nav.init_map(); $('.locationinput').data('location', null); var state = JSON.parse($('main').attr('data-state')); history.replaceState(state, window.location.path); c3nav.load_state(state, true); c3nav.update_map_locations(); c3nav._push_state(state, true); if (!state.center) { if (state.origin || state.destination) { c3nav.fly_to_bounds(true, true); } else { c3nav.update_map_state(true); } } c3nav.init_locationinputs(); $('#location-buttons').find('.route').on('click', c3nav._location_buttons_route_click); $('#route-search-buttons, #route-result-buttons').find('.swap').on('click', c3nav._route_buttons_swap_click); $('#route-search-buttons, #route-summary').find('.close').on('click', c3nav._route_buttons_close_click); $('#map').on('click', '.location-popup .button-clear', c3nav._popup_button_click); window.onpopstate = c3nav._onpopstate; }, state: {}, update_state: function(routing, replace) { if (typeof routing !== "boolean") routing = c3nav.state.routing; var destination = $('#destination-input').data('location'), origin = $('#origin-input').data('location'), new_state = { routing: routing, origin: origin, destination: destination, sidebar: true }; c3nav._push_state(new_state, replace); c3nav._sidebar_state_updated(new_state); }, update_map_state: function (replace, level, center, zoom) { var new_state = { level: center ? level : c3nav._levelControl.currentLevel, center: L.GeoJSON.latLngToCoords(center ? center : c3nav.map.getCenter(), 2), zoom: Math.round((center ? zoom : c3nav.map.getZoom()) * 100) / 100 }; if (!replace) new_state.sidebar = false; c3nav._push_state(new_state, replace); }, _sidebar_state_updated: function (state) { var view; if (state.routing) { view = (!state.origin || !state.destination) ? 'route-search' : 'route-result'; } else { view = state.destination ? 'location' : 'search'; if (state.origin) { c3nav._locationinput_set($('#origin_input'), null); } } c3nav._view = view; $('main').attr('data-view', view); $('.locationinput.selected:focus').blur(); $('#destination-input, [data-view^=route] #origin-input').filter(':not(.selected)').find('input').first().focus(); c3nav.update_map_locations(); }, _equal_states: function (a, b) { if (a.routing !== b.routing) return false; if ((a.origin && a.origin.id) !== (b.origin && b.origin.id)) return false; if ((a.destination && a.destination.id) !== (b.destination && b.destination.id)) return false; if (a.level !== b.level || a.zoom !== b.zoom) return false; if (a.center[0] !== b.center[0] || a.center[1] !== b.center[1]) return false; return true; }, _push_state: function (state, replace) { state = $.extend({}, c3nav.state, state); var old_state = c3nav.state; if (!replace && c3nav._equal_states(old_state, state)) return; var url; if (state.routing) { if (state.origin) { url = (state.destination) ? '/r/'+state.origin.slug+'/'+state.destination.slug+'/' : '/o/'+state.origin.slug+'/'; } else { url = (state.destination) ? '/d/'+state.destination.slug+'/' : '/r/'; } } else { url = state.destination?('/l/'+state.destination.slug+'/'):'/'; } if (state.center) { url += '@'+String(c3nav.level_labels_by_id[state.level])+','+String(state.center[0])+','+String(state.center[1])+','+String(state.zoom); } c3nav.state = state; if (replace || (!state.sidebar && !old_state.sidebar)) { // console.log('state replaced'); history.replaceState(state, '', url); } else { // console.log('state pushed'); history.pushState(state, '', url); } }, _onpopstate: function (e) { // console.log('state popped'); c3nav.load_state(e.state); }, load_state: function (state, nofly) { c3nav._locationinput_set($('#origin-input'), state.origin); c3nav._locationinput_set($('#destination-input'), state.destination); c3nav._sidebar_state_updated(state); if (state.center) { c3nav._levelControl.setLevel(state.level); var center = c3nav.map._limitCenter(L.GeoJSON.coordsToLatLng(state.center), state.zoom, c3nav.map.options.maxBounds); if (nofly) { c3nav.map.setView(center, state.zoom, {animate: false}); } else { c3nav.map.flyTo(center, state.zoom, {duration: 1}); } } $.extend(c3nav.state, state); }, // button handlers _location_buttons_route_click: function () { c3nav.update_state(true); }, _route_buttons_swap_click: function () { var $origin = $('#origin-input'), $destination = $('#destination-input'), tmp = $origin.data('location'); c3nav._locationinput_set($origin, $destination.data('location')); c3nav._locationinput_set($destination, tmp); $origin.stop().css('top', '55px').animate({top: 0}, 150); $destination.stop().css('top', '-55px').animate({top: 0}, 150); c3nav.update_state(); }, _route_buttons_close_click: function () { var $origin = $('#origin-input'), $destination = $('#destination-input'); if ($origin.is('.selected') && !$destination.is('.selected')) { c3nav._locationinput_set($destination, $origin.data('location')); } c3nav.update_state(false); }, _popup_button_click: function () { var location = c3nav.locations_by_id[parseInt($(this).siblings('.location').attr('data-id'))], $origin = $('#origin-input'), $destination = $('#destination-input'); if ($(this).is('.as-location')) { c3nav._locationinput_set($destination, location); c3nav.update_state(false); } else { var $locationinput = $(this).is('.as-origin') ? $origin : $destination, $other_locationinput = $(this).is('.as-origin') ? $destination : $origin, other_location = $other_locationinput.data('location'); c3nav._locationinput_set($locationinput, location); if (other_location && (other_location.id === location.id || (other_location.locations && other_location.locations.includes(location.id)))) { c3nav._locationinput_set($other_locationinput, null); } c3nav.update_state(true); } }, // location inputs init_locationinputs: function () { c3nav.locations = []; c3nav.locations_by_id = {}; c3nav.current_locationinput = null; c3nav._last_match_words_key = null; $.getJSON('/api/locations/?searchable', function (data) { for (var i = 0; i < data.length; i++) { var location = data[i]; location.elem = $('<div class="location">').append($('<span>').text(location.title)) .append($('<small>').text(location.subtitle)).attr('data-id', location.id)[0].outerHTML; location.title_words = location.title.toLowerCase().split(/\s+/); location.match = ' ' + location.title_words.join(' ') + ' '; c3nav.locations.push(location); c3nav.locations_by_id[location.id] = location; } }); $('.locationinput input').on('input', c3nav._locationinput_input) .on('blur', c3nav._locationinput_blur) .on('keydown', c3nav._locationinput_keydown); $('.locationinput .clear').on('click', c3nav._locationinput_clear); $('#autocomplete').on('mouseover', '.location', c3nav._locationinput_hover_suggestion) .on('click', '.location', c3nav._locationinput_click_suggestion); $('html').on('focus', '*', c3nav._locationinput_global_focuschange); }, _locationinput_set: function (elem, location) { // set a location input c3nav._locationinput_reset_autocomplete(); elem.toggleClass('selected', !!location).toggleClass('empty', !location) .data('location', location).data('lastlocation', location).removeData('suggestion'); elem.find('input').val(location ? location.title : '').removeData('origval'); elem.find('small').text(location ? location.subtitle : ''); }, _locationinput_reset: function (elem) { // reset this locationinput to its last location c3nav._locationinput_set(elem, elem.data('lastlocation')); c3nav.update_state(); }, _locationinput_clear: function () { // clear this locationinput c3nav._locationinput_set($(this).parent(), null); c3nav.update_state(); $(this).parent().find('input').focus(); }, _locationinput_reset_autocomplete: function () { // hide autocomplete var $autocomplete = $('#autocomplete'); $autocomplete.find('.focus').removeClass('focus'); $autocomplete.html(''); c3nav._last_locationinput_words_key = null; c3nav.current_locationinput = null; }, _locationinput_blur: function () { // when a locationinput is blurred… var suggestion = $(this).parent().data('suggestion'); if (suggestion) { // if it has a suggested location in it currently c3nav._locationinput_set($(this).parent(), suggestion); c3nav.update_state(); } else { // otherwise, forget the last location $(this).parent().data('lastlocation', null); } }, _locationinput_global_focuschange: function () { // when focus changed, reset autocomplete if it is outside of locationinputs or autocomplete if (!c3nav.current_locationinput) return; if (!$('#autocomplete > :focus, #' + c3nav.current_locationinput + ' > :focus').length) { c3nav._locationinput_reset_autocomplete(); } }, _locationinput_keydown: function (e) { var $autocomplete = $('#autocomplete'), $focused, origval; if (e.which === 27) { // escape: reset the location input origval = $(this).data('origval'); if (origval) { $(this).val(origval).removeData('origval'); $(this).parent().removeData('suggestion'); $autocomplete.find('.focus').removeClass('focus'); } else { c3nav._locationinput_reset($(this).parent()); } } else if (e.which === 40 || e.which === 38) { // arrows up/down var $locations = $autocomplete.find('.location'); if (!$locations.length) return; // save current input value in case we have to restore it if (!$(this).data('origval')) { $(this).data('origval', $(this).val()) } // find focused element and remove focus $focused = $locations.filter('.focus'); $locations.removeClass('focus'); // find next element var next; if (!$focused.length) { next = $locations.filter((e.which === 40) ? ':first-child' : ':last-child'); } else { next = (e.which === 40) ? $focused.next() : $focused.prev(); } if (!next.length) { // if there is no next element, restore original value $(this).val($(this).data('origval')).parent().removeData('suggestion'); } else { // otherwise, focus this element, and save location to the input next.addClass('focus'); $(this).val(next.find('span').text()).parent() .data('suggestion', c3nav.locations_by_id[next.attr('data-id')]); } } else if (e.which === 13) { // enter: select currently focused suggestion or first suggestion $focused = $autocomplete.find('.location.focus'); if (!$focused.length) { $focused = $autocomplete.find('.location:first-child'); } if (!$focused.length) return; c3nav._locationinput_set($(this).parent(), c3nav.locations_by_id[$focused.attr('data-id')]); c3nav.update_state(); c3nav.fly_to_bounds(true); } }, _locationinput_hover_suggestion: function () { $(this).addClass('focus').siblings().removeClass('focus'); }, _locationinput_click_suggestion: function () { var $locationinput = $('#' + c3nav.current_locationinput); c3nav._locationinput_set($locationinput, c3nav.locations_by_id[$(this).attr('data-id')]); c3nav.update_state(); c3nav.fly_to_bounds(true); }, _locationinput_matches_compare: function (a, b) { if (a[1] !== b[1]) return b[1] - a[1]; if (a[2] !== b[2]) return b[2] - a[2]; if (a[3] !== b[3]) return b[3] - a[3]; return a[4] - b[4]; }, _locationinput_input: function () { var matches = [], val = $(this).removeData('origval').val(), val_trimmed = $.trim(val), val_words = val_trimmed.toLowerCase().split(/\s+/), val_words_key = val_words.join(' '), $autocomplete = $('#autocomplete'), $parent = $(this).parent(); $parent.toggleClass('empty', val === '').removeData('suggestion'); if ($parent.is('.selected')) { $parent.removeClass('selected').data('location', null); c3nav.update_state(); } $autocomplete.find('.focus').removeClass('focus'); c3nav.current_locationinput = $parent.attr('id'); if (val_trimmed === '') { c3nav._locationinput_reset_autocomplete(); return; } if (val_words_key === c3nav._last_locationinput_words_key) return; c3nav._last_locationinput_words_key = val_words_key; for (var i = 0; i < c3nav.locations.length; i++) { var location = c3nav.locations[i], leading_words_count = 0, words_total_count = 0, words_start_count = 0, nomatch = false, val_word, j; // each word has to be in the location for (j = 0; j < val_words.length; j++) { val_word = val_words[j]; if (location.match.indexOf(val_word) === -1) { nomatch = true; break; } } if (nomatch) continue; // how many words from the beginning are in the title for (j = 0; j < val_words.length; j++) { val_word = val_words[0]; if (location.title_words[j] !== val_word && (j !== val_words.length - 1 || location.title_words[j].indexOf(val_word) !== 0)) break; leading_words_count++; } // how many words in total can be found for (j = 0; j < val_words.length; j++) { val_word = val_words[0]; if (location.match.indexOf(' ' + val_word + ' ') !== -1) { words_total_count++; } else if (location.match.indexOf(' ' + val_word) !== -1) { words_start_count++; } } matches.push([location.elem, leading_words_count, words_total_count, words_start_count, i]) } matches.sort(c3nav._locationinput_matches_compare); $autocomplete.html(''); var max_items = Math.min(matches.length, Math.floor($('#resultswrapper').height() / 55)); for (i = 0; i < max_items; i++) { $autocomplete.append(matches[i][0]); } }, // map init_map: function () { var $map = $('#map'), i; c3nav.bounds = JSON.parse($map.attr('data-bounds')); c3nav.levels = JSON.parse($map.attr('data-levels')); c3nav.level_labels_by_id = {}; for (i = 0; i < c3nav.levels.length; i ++) { c3nav.level_labels_by_id[c3nav.levels[i][0]] = c3nav.levels[i][1]; } // create leaflet map c3nav.map = L.map('map', { renderer: L.svg({padding: 2}), zoom: 2, maxZoom: 10, minZoom: 0, crs: L.CRS.Simple, maxBounds: L.GeoJSON.coordsToLatLngs(c3nav.bounds), zoomSnap: 0, zoomControl: false }); if (L.Browser.chrome && !('ontouchstart' in window)) { $('.leaflet-touch').removeClass('leaflet-touch'); } c3nav.map.fitBounds(L.GeoJSON.coordsToLatLngs(c3nav.bounds), c3nav._add_map_padding({})); c3nav.map.on('moveend', c3nav._map_moved); c3nav.map.on('zoomend', c3nav._map_zoomed); // set up icons L.Icon.Default.imagePath = '/static/leaflet/images/'; c3nav._add_icon('origin'); c3nav._add_icon('destination'); // setup scale control L.control.scale({imperial: false}).addTo(c3nav.map); // setup level control c3nav._levelControl = new LevelControl().addTo(c3nav.map); c3nav._locationLayers = {}; c3nav._locationLayerBounds = {}; c3nav._routeLayers = {}; for (i = c3nav.levels.length - 1; i >= 0; i--) { var level = c3nav.levels[i]; var layerGroup = c3nav._levelControl.addLevel(level[0], level[2]); c3nav._locationLayers[level[0]] = L.layerGroup().addTo(layerGroup); c3nav._routeLayers[level[0]] = L.layerGroup().addTo(layerGroup); } c3nav._levelControl.finalize(); c3nav._levelControl.setLevel(c3nav.levels[0][0]); c3nav.schedule_refresh_tile_access(); }, _map_moved: function () { c3nav.update_map_state(); }, _map_zoomed: function () { c3nav.update_map_state(); }, _add_icon: function (name) { c3nav[name+'Icon'] = new L.Icon({ iconUrl: '/static/img/marker-icon-'+name+'.png', iconRetinaUrl: '/static/img/marker-icon-\'+name+\'-2x.png', shadowUrl: '/static/leaflet/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], tooltipAnchor: [16, -28], shadowSize: [41, 41] }); }, update_map_locations: function () { // update locations markers on the map var origin = $('#origin-input').data('location'), destination = $('#destination-input').data('location'), single = !$('main').is('[data-view^=route]'), bounds = {}; for (var level_id in c3nav._locationLayers) { c3nav._locationLayers[level_id].clearLayers() } if (origin) c3nav._merge_bounds(bounds, c3nav._add_location_to_map(origin, single ? new L.Icon.Default() : c3nav.originIcon)); if (destination) c3nav._merge_bounds(bounds, c3nav._add_location_to_map(destination, single ? new L.Icon.Default() : c3nav.destinationIcon)); c3nav._locationLayerBounds = bounds; }, fly_to_bounds: function(replace_state, nofly) { // fly to the bounds of the current overlays var level = c3nav._levelControl.currentLevel, bounds = null; if (c3nav._locationLayerBounds[level]) { bounds = c3nav._locationLayerBounds[level]; } else { for (var level_id in c3nav._locationLayers) { if (c3nav._locationLayerBounds[level_id]) { bounds = c3nav._locationLayerBounds[level_id]; level = level_id } } } c3nav._levelControl.setLevel(level); if (bounds) { var left = 0, top = (left === 0) ? $('#search').height()+10 : 10, target = c3nav.map._getBoundsCenterZoom(bounds, c3nav._add_map_padding({})), center = c3nav.map._limitCenter(target.center, target.zoom, c3nav.map.options.maxBounds); if (nofly) { c3nav.map.flyTo(center, target.zoom, { animate: false }); } else { c3nav.map.flyTo(center, target.zoom, { duration: 1 }); } if (replace_state) { c3nav.update_map_state(true, level, center, target.zoom); } } }, _add_map_padding: function(options, topleft, bottomright) { // add padding information for the current ui layout to fitBoudns options var left = 0, top = (left === 0) ? $('#search').height()+10 : 10; options[topleft || 'paddingTopLeft'] = L.point(left+13, top+41); options[bottomright || 'paddingBottomRight'] = L.point(50, 20); return options; }, _add_location_to_map: function(location, icon) { // add a location to the map as a marker if (location.locations) { var bounds = {}; for (var i=0; i<location.locations.length; i++) { c3nav._merge_bounds(bounds, c3nav._add_location_to_map(c3nav.locations_by_id[location.locations[i]], icon)); } return bounds; } var latlng = L.GeoJSON.coordsToLatLng(location.point.slice(1)); L.marker(latlng, { icon: icon }).bindPopup(location.elem+$('#popup-buttons').html(), c3nav._add_map_padding({ className: 'location-popup' }, 'autoPanPaddingTopLeft', 'autoPanPaddingBottomRight')).addTo(c3nav._locationLayers[location.point[0]]); var result = {}; result[location.point[0]] = L.latLngBounds( location.bounds ? L.GeoJSON.coordsToLatLngs(location.bounds) : [latlng, latlng] ); return result }, _merge_bounds: function(bounds, new_bounds) { for (var level_id in new_bounds) { bounds[level_id] = bounds[level_id] ? bounds[level_id].extend(new_bounds[level_id]) : new_bounds[level_id]; } }, schedule_refresh_tile_access: function () { window.setTimeout(c3nav.refresh_tile_access, 16000); }, refresh_tile_access: function () { $.ajax('/map/tile_access'); c3nav.schedule_refresh_tile_access(); } }; $(document).ready(c3nav.init); LevelControl = L.Control.extend({ options: { position: 'bottomright', addClasses: '' }, onAdd: function () { this._container = L.DomUtil.create('div', 'leaflet-control-levels leaflet-bar ' + this.options.addClasses); this._tileLayers = {}; this._overlayLayers = {}; this._levelButtons = {}; this.currentLevel = null; return this._container; }, addLevel: function (id, title) { this._tileLayers[id] = L.tileLayer('/map/' + String(id) + '/{z}/{x}/{y}.png', { bounds: L.GeoJSON.coordsToLatLngs(c3nav.bounds) }); var overlay = L.layerGroup(); this._overlayLayers[id] = overlay; var link = L.DomUtil.create('a', '', this._container); link.innerHTML = title; link.level = id; link.href = '#'; L.DomEvent .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation) .on(link, 'click', this._levelClick, this); this._levelButtons[id] = link; return overlay; }, setLevel: function (id) { if (id === this.currentLevel) return true; if (this._tileLayers[id] === undefined) return false; if (this.currentLevel) { this._tileLayers[this.currentLevel].remove(); this._overlayLayers[this.currentLevel].remove(); L.DomUtil.removeClass(this._levelButtons[this.currentLevel], 'current'); } this._tileLayers[id].addTo(c3nav.map); this._overlayLayers[id].addTo(c3nav.map); L.DomUtil.addClass(this._levelButtons[id], 'current'); this.currentLevel = id; return true; }, _levelClick: function (e) { e.preventDefault(); e.stopPropagation(); this.setLevel(e.target.level); c3nav.update_map_state(); }, finalize: function () { var buttons = $(this._container).find('a'); buttons.addClass('current'); buttons.width(buttons.width()); buttons.removeClass('current'); } });
src/c3nav/site/static/site/js/c3nav.js
(function () { /* * Workaround for 1px lines appearing in some browsers due to fractional transforms * and resulting anti-aliasing. * https://github.com/Leaflet/Leaflet/issues/3575 */ var originalInitTile = L.GridLayer.prototype._initTile; L.GridLayer.include({ _initTile: function (tile) { originalInitTile.call(this, tile); var tileSize = this.getTileSize(); tile.style.width = tileSize.x + 1 + 'px'; tile.style.height = tileSize.y + 1 + 'px'; } }); }()); c3nav = { init: function () { c3nav.init_map(); $('.locationinput').data('location', null); var state = JSON.parse($('main').attr('data-state')); history.replaceState(state, window.location.path); c3nav.load_state(state, true); c3nav.update_map_locations(); c3nav._push_state(state, true); if (!state.center) { if (state.origin || state.destination) { c3nav.fly_to_bounds(true, true); } else { c3nav.update_map_state(true); } } c3nav.init_locationinputs(); $('#location-buttons').find('.route').on('click', c3nav._location_buttons_route_click); $('#route-search-buttons, #route-result-buttons').find('.swap').on('click', c3nav._route_buttons_swap_click); $('#route-search-buttons, #route-summary').find('.close').on('click', c3nav._route_buttons_close_click); $('#map').on('click', '.location-popup .button-clear', c3nav._popup_button_click); window.onpopstate = c3nav._onpopstate; }, state: {}, update_state: function(routing, replace) { if (typeof routing !== "boolean") routing = c3nav.state.routing; var destination = $('#destination-input').data('location'), origin = $('#origin-input').data('location'), new_state = { routing: routing, origin: origin, destination: destination, sidebar: true }; c3nav._push_state(new_state, replace); c3nav._sidebar_state_updated(new_state); }, update_map_state: function (replace, level, center, zoom) { var new_state = { level: center ? level : c3nav._levelControl.currentLevel, center: L.GeoJSON.latLngToCoords(center ? center : c3nav.map.getCenter(), 2), zoom: Math.round((center ? zoom : c3nav.map.getZoom()) * 100) / 100 }; if (!replace) new_state.sidebar = false; c3nav._push_state(new_state, replace); }, _sidebar_state_updated: function (state) { var view; if (state.routing) { view = (!state.origin || !state.destination) ? 'route-search' : 'route-result'; } else { view = state.destination ? 'location' : 'search'; if (state.origin) { c3nav._locationinput_set($('#origin_input'), null); } } c3nav._view = view; $('main').attr('data-view', view); $('.locationinput.selected:focus').blur(); $('#destination-input, [data-view^=route] #origin-input').filter(':not(.selected)').find('input').first().focus(); c3nav.update_map_locations(); }, _equal_states: function (a, b) { if (a.routing !== b.routing) return false; if ((a.origin && a.origin.id) !== (b.origin && b.origin.id)) return false; if ((a.destination && a.destination.id) !== (b.destination && b.destination.id)) return false; if (a.level !== b.level || a.zoom !== b.zoom) return false; if (a.center[0] !== b.center[0] || a.center[1] !== b.center[1]) return false; return true; }, _push_state: function (state, replace) { state = $.extend({}, c3nav.state, state); var old_state = c3nav.state; if (!replace && c3nav._equal_states(old_state, state)) return; var url; if (state.routing) { if (state.origin) { url = (state.destination) ? '/r/'+state.origin.slug+'/'+state.destination.slug+'/' : '/o/'+state.origin.slug+'/'; } else { url = (state.destination) ? '/d/'+state.destination.slug+'/' : '/r/'; } } else { url = state.destination?('/l/'+state.destination.slug+'/'):'/'; } if (state.center) { url += '@'+String(c3nav.level_labels_by_id[state.level])+','+String(state.center[0])+','+String(state.center[1])+','+String(state.zoom); } c3nav.state = state; if (replace || (!state.sidebar && !old_state.sidebar)) { // console.log('state replaced'); history.replaceState(state, '', url); } else { // console.log('state pushed'); history.pushState(state, '', url); } }, _onpopstate: function (e) { // console.log('state popped'); c3nav.load_state(e.state); }, load_state: function (state, nofly) { c3nav._locationinput_set($('#origin-input'), state.origin); c3nav._locationinput_set($('#destination-input'), state.destination); c3nav._sidebar_state_updated(state); if (state.center) { c3nav._levelControl.setLevel(state.level); var center = c3nav.map._limitCenter(L.GeoJSON.coordsToLatLng(state.center), state.zoom, c3nav.map.options.maxBounds); if (nofly) { c3nav.map.setView(center, state.zoom, {animate: false}); } else { c3nav.map.flyTo(center, state.zoom, {duration: 1}); } } $.extend(c3nav.state, state); }, // button handlers _location_buttons_route_click: function () { c3nav.update_state(true); }, _route_buttons_swap_click: function () { var $origin = $('#origin-input'), $destination = $('#destination-input'), tmp = $origin.data('location'); c3nav._locationinput_set($origin, $destination.data('location')); c3nav._locationinput_set($destination, tmp); $origin.stop().css('top', '55px').animate({top: 0}, 150); $destination.stop().css('top', '-55px').animate({top: 0}, 150); c3nav.update_state(); }, _route_buttons_close_click: function () { var $origin = $('#origin-input'), $destination = $('#destination-input'); if ($origin.is('.selected') && !$destination.is('.selected')) { c3nav._locationinput_set($destination, $origin.data('location')); } c3nav.update_state(false); }, _popup_button_click: function () { var location = c3nav.locations_by_id[parseInt($(this).siblings('.location').attr('data-id'))], $origin = $('#origin-input'), $destination = $('#destination-input'); if ($(this).is('.as-location')) { c3nav._locationinput_set($destination, location); c3nav.update_state(false); } else { var $locationinput = $(this).is('.as-origin') ? $origin : $destination, $other_locationinput = $(this).is('.as-origin') ? $destination : $origin, other_location = $other_locationinput.data('location'); c3nav._locationinput_set($locationinput, location); if (other_location && (other_location.id === location.id || (other_location.locations && other_location.locations.includes(location.id)))) { c3nav._locationinput_set($other_locationinput, null); } c3nav.update_state(true); } }, // location inputs init_locationinputs: function () { c3nav.locations = []; c3nav.locations_by_id = {}; c3nav.current_locationinput = null; c3nav._last_match_words_key = null; $.getJSON('/api/locations/?searchable', function (data) { for (var i = 0; i < data.length; i++) { var location = data[i]; location.elem = $('<div class="location">').append($('<span>').text(location.title)) .append($('<small>').text(location.subtitle)).attr('data-id', location.id)[0].outerHTML; location.title_words = location.title.toLowerCase().split(/\s+/); location.match = ' ' + location.title_words.join(' ') + ' '; c3nav.locations.push(location); c3nav.locations_by_id[location.id] = location; } }); $('.locationinput input').on('input', c3nav._locationinput_input) .on('blur', c3nav._locationinput_blur) .on('keydown', c3nav._locationinput_keydown); $('.locationinput .clear').on('click', c3nav._locationinput_clear); $('#autocomplete').on('mouseover', '.location', c3nav._locationinput_hover_suggestion) .on('click', '.location', c3nav._locationinput_click_suggestion); $('html').on('focus', '*', c3nav._locationinput_global_focuschange); }, _locationinput_set: function (elem, location) { // set a location input c3nav._locationinput_reset_autocomplete(); elem.toggleClass('selected', !!location).toggleClass('empty', !location) .data('location', location).data('lastlocation', location).removeData('suggestion'); elem.find('input').val(location ? location.title : '').removeData('origval'); elem.find('small').text(location ? location.subtitle : ''); }, _locationinput_reset: function (elem) { // reset this locationinput to its last location c3nav._locationinput_set(elem, elem.data('lastlocation')); c3nav.update_state(); }, _locationinput_clear: function () { // clear this locationinput c3nav._locationinput_set($(this).parent(), null); c3nav.update_state(); $(this).parent().find('input').focus(); }, _locationinput_reset_autocomplete: function () { // hide autocomplete var $autocomplete = $('#autocomplete'); $autocomplete.find('.focus').removeClass('focus'); $autocomplete.html(''); c3nav._last_locationinput_words_key = null; c3nav.current_locationinput = null; }, _locationinput_blur: function () { // when a locationinput is blurred… var suggestion = $(this).parent().data('suggestion'); if (suggestion) { // if it has a suggested location in it currently c3nav._locationinput_set($(this).parent(), suggestion); c3nav.update_state(); } else { // otherwise, forget the last location $(this).parent().data('lastlocation', null); } }, _locationinput_global_focuschange: function () { // when focus changed, reset autocomplete if it is outside of locationinputs or autocomplete if (!c3nav.current_locationinput) return; if (!$('#autocomplete > :focus, #' + c3nav.current_locationinput + ' > :focus').length) { c3nav._locationinput_reset_autocomplete(); } }, _locationinput_keydown: function (e) { var $autocomplete = $('#autocomplete'), $focused, origval; if (e.which === 27) { // escape: reset the location input origval = $(this).data('origval'); if (origval) { $(this).val(origval).removeData('origval'); $(this).parent().removeData('suggestion'); $autocomplete.find('.focus').removeClass('focus'); } else { c3nav._locationinput_reset($(this).parent()); } } else if (e.which === 40 || e.which === 38) { // arrows up/down var $locations = $autocomplete.find('.location'); if (!$locations.length) return; // save current input value in case we have to restore it if (!$(this).data('origval')) { $(this).data('origval', $(this).val()) } // find focused element and remove focus $focused = $locations.filter('.focus'); $locations.removeClass('focus'); // find next element var next; if (!$focused.length) { next = $locations.filter((e.which === 40) ? ':first-child' : ':last-child'); } else { next = (e.which === 40) ? $focused.next() : $focused.prev(); } if (!next.length) { // if there is no next element, restore original value $(this).val($(this).data('origval')).parent().removeData('suggestion'); } else { // otherwise, focus this element, and save location to the input next.addClass('focus'); $(this).val(next.find('span').text()).parent() .data('suggestion', c3nav.locations_by_id[next.attr('data-id')]); } } else if (e.which === 13) { // enter: select currently focused suggestion or first suggestion $focused = $autocomplete.find('.location.focus'); if (!$focused.length) { $focused = $autocomplete.find('.location:first-child'); } if (!$focused.length) return; c3nav._locationinput_set($(this).parent(), c3nav.locations_by_id[$focused.attr('data-id')]); c3nav.update_state(); c3nav.fly_to_bounds(true); } }, _locationinput_hover_suggestion: function () { $(this).addClass('focus').siblings().removeClass('focus'); }, _locationinput_click_suggestion: function () { var $locationinput = $('#' + c3nav.current_locationinput); c3nav._locationinput_set($locationinput, c3nav.locations_by_id[$(this).attr('data-id')]); c3nav.update_state(); c3nav.fly_to_bounds(true); }, _locationinput_matches_compare: function (a, b) { if (a[1] !== b[1]) return b[1] - a[1]; if (a[2] !== b[2]) return b[2] - a[2]; if (a[3] !== b[3]) return b[3] - a[3]; return a[4] - b[4]; }, _locationinput_input: function () { var matches = [], val = $(this).removeData('origval').val(), val_trimmed = $.trim(val), val_words = val_trimmed.toLowerCase().split(/\s+/), val_words_key = val_words.join(' '), $autocomplete = $('#autocomplete'), $parent = $(this).parent(); $parent.toggleClass('empty', val === '').removeData('suggestion'); if ($parent.is('.selected')) { $parent.removeClass('selected').data('location', null); c3nav.update_state(); } $autocomplete.find('.focus').removeClass('focus'); c3nav.current_locationinput = $parent.attr('id'); if (val_trimmed === '') { c3nav._locationinput_reset_autocomplete(); return; } if (val_words_key === c3nav._last_locationinput_words_key) return; c3nav._last_locationinput_words_key = val_words_key; for (var i = 0; i < c3nav.locations.length; i++) { var location = c3nav.locations[i], leading_words_count = 0, words_total_count = 0, words_start_count = 0, nomatch = false, val_word, j; // each word has to be in the location for (j = 0; j < val_words.length; j++) { val_word = val_words[j]; if (location.match.indexOf(val_word) === -1) { nomatch = true; break; } } if (nomatch) continue; // how many words from the beginning are in the title for (j = 0; j < val_words.length; j++) { val_word = val_words[0]; if (location.title_words[j] !== val_word && (j !== val_words.length - 1 || location.title_words[j].indexOf(val_word) !== 0)) break; leading_words_count++; } // how many words in total can be found for (j = 0; j < val_words.length; j++) { val_word = val_words[0]; if (location.match.indexOf(' ' + val_word + ' ') !== -1) { words_total_count++; } else if (location.match.indexOf(' ' + val_word) !== -1) { words_start_count++; } } matches.push([location.elem, leading_words_count, words_total_count, words_start_count, i]) } matches.sort(c3nav._locationinput_matches_compare); $autocomplete.html(''); var max_items = Math.min(matches.length, Math.floor($('#resultswrapper').height() / 55)); for (i = 0; i < max_items; i++) { $autocomplete.append(matches[i][0]); } }, // map init_map: function () { var $map = $('#map'), i; c3nav.bounds = JSON.parse($map.attr('data-bounds')); c3nav.levels = JSON.parse($map.attr('data-levels')); c3nav.level_labels_by_id = {}; for (i = 0; i < c3nav.levels.length; i ++) { c3nav.level_labels_by_id[c3nav.levels[i][0]] = c3nav.levels[i][1]; } // create leaflet map c3nav.map = L.map('map', { renderer: L.svg({padding: 2}), zoom: 2, maxZoom: 10, minZoom: 0, crs: L.CRS.Simple, maxBounds: L.GeoJSON.coordsToLatLngs(c3nav.bounds), zoomSnap: 0, zoomControl: false }); if (L.Browser.chrome && !('ontouchstart' in window)) { $('.leaflet-touch').removeClass('leaflet-touch'); } c3nav.map.fitBounds(L.GeoJSON.coordsToLatLngs(c3nav.bounds), c3nav._add_map_padding({})); c3nav.map.on('moveend', c3nav._map_moved); c3nav.map.on('zoomend', c3nav._map_zoomed); // set up icons L.Icon.Default.imagePath = '/static/leaflet/images/'; c3nav._add_icon('origin'); c3nav._add_icon('destination'); // setup scale control L.control.scale({imperial: false}).addTo(c3nav.map); // setup level control c3nav._levelControl = new LevelControl().addTo(c3nav.map); c3nav._locationLayers = {}; c3nav._locationLayerBounds = {}; c3nav._routeLayers = {}; for (i = c3nav.levels.length - 1; i >= 0; i--) { var level = c3nav.levels[i]; var layerGroup = c3nav._levelControl.addLevel(level[0], level[2]); c3nav._locationLayers[level[0]] = L.layerGroup().addTo(layerGroup); c3nav._routeLayers[level[0]] = L.layerGroup().addTo(layerGroup); } c3nav._levelControl.finalize(); c3nav._levelControl.setLevel(c3nav.levels[0][0]); c3nav.schedule_refresh_tile_access(); }, _map_moved: function () { c3nav.update_map_state(); }, _map_zoomed: function () { c3nav.update_map_state(); }, _add_icon: function (name) { c3nav[name+'Icon'] = new L.Icon({ iconUrl: '/static/img/marker-icon-'+name+'.png', iconRetinaUrl: '/static/img/marker-icon-\'+name+\'-2x.png', shadowUrl: '/static/leaflet/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], tooltipAnchor: [16, -28], shadowSize: [41, 41] }); }, update_map_locations: function () { // update locations markers on the map var origin = $('#origin-input').data('location'), destination = $('#destination-input').data('location'), single = !$('main').is('[data-view^=route]'), bounds = {}; for (var level_id in c3nav._locationLayers) { c3nav._locationLayers[level_id].clearLayers() } if (origin) c3nav._merge_bounds(bounds, c3nav._add_location_to_map(origin, single ? new L.Icon.Default() : c3nav.originIcon)); if (destination) c3nav._merge_bounds(bounds, c3nav._add_location_to_map(destination, single ? new L.Icon.Default() : c3nav.destinationIcon)); c3nav._locationLayerBounds = bounds; }, fly_to_bounds: function(replace_state, nofly) { // fly to the bounds of the current overlays var level = c3nav._levelControl.currentLevel, bounds = null; if (c3nav._locationLayerBounds[level]) { bounds = c3nav._locationLayerBounds[level]; } else { for (var level_id in c3nav._locationLayers) { if (c3nav._locationLayerBounds[level_id]) { bounds = c3nav._locationLayerBounds[level_id]; level = level_id } } } c3nav._levelControl.setLevel(level); if (bounds) { var left = 0, top = (left === 0) ? $('#search').height()+10 : 10, target = c3nav.map._getBoundsCenterZoom(bounds, c3nav._add_map_padding({})), center = c3nav.map._limitCenter(target.center, target.zoom, c3nav.map.options.maxBounds); if (nofly) { c3nav.map.flyTo(center, target.zoom, { animate: false }); } else { c3nav.map.flyTo(center, target.zoom, { duration: 1 }); } if (replace_state) { c3nav.update_map_state(true, level, center, target.zoom); } } }, _add_map_padding: function(options, topleft, bottomright) { // add padding information for the current ui layout to fitBoudns options var left = 0, top = (left === 0) ? $('#search').height()+10 : 10; options[topleft || 'paddingTopLeft'] = L.point(left+13, top+41); options[bottomright || 'paddingBottomRight'] = L.point(50, 20); return options; }, _add_location_to_map: function(location, icon) { // add a location to the map as a marker if (location.locations) { var bounds = {}; for (var i=0; i<location.locations.length; i++) { c3nav._merge_bounds(bounds, c3nav._add_location_to_map(c3nav.locations_by_id[location.locations[i]], icon)); } return bounds; } var latlng = L.GeoJSON.coordsToLatLng(location.point.slice(1)); L.marker(latlng, { icon: icon }).bindPopup(location.elem+$('#popup-buttons').html(), c3nav._add_map_padding({ className: 'location-popup' }, 'autoPanPaddingTopLeft', 'autoPanPaddingBottomRight')).addTo(c3nav._locationLayers[location.point[0]]); var result = {}; result[location.point[0]] = L.latLngBounds( location.bounds ? L.GeoJSON.coordsToLatLngs(location.bounds) : [latlng, latlng] ); return result }, _merge_bounds: function(bounds, new_bounds) { for (var level_id in new_bounds) { bounds[level_id] = bounds[level_id] ? bounds[level_id].extend(new_bounds[level_id]) : new_bounds[level_id]; } }, schedule_refresh_tile_access: function () { window.setTimeout(c3nav.refresh_tile_access, 16000); }, refresh_tile_access: function () { $.ajax('/map/tile_access'); c3nav.schedule_refresh_tile_access(); } }; $(document).ready(c3nav.init); LevelControl = L.Control.extend({ options: { position: 'bottomright', addClasses: '' }, onAdd: function () { this._container = L.DomUtil.create('div', 'leaflet-control-levels leaflet-bar ' + this.options.addClasses); this._tileLayers = {}; this._overlayLayers = {}; this._levelButtons = {}; this.currentLevel = null; return this._container; }, addLevel: function (id, title) { this._tileLayers[id] = L.tileLayer('/map/' + String(id) + '/{z}/{x}/{y}.png', { bounds: L.GeoJSON.coordsToLatLngs(c3nav.bounds) }); var overlay = L.layerGroup(); this._overlayLayers[id] = overlay; var link = L.DomUtil.create('a', '', this._container); link.innerHTML = title; link.level = id; link.href = '#'; L.DomEvent .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation) .on(link, 'click', this._levelClick, this); this._levelButtons[id] = link; return overlay; }, setLevel: function (id) { if (id === this.currentLevel) return true; if (this._tileLayers[id] === undefined) return false; if (this.currentLevel) { this._tileLayers[this.currentLevel].remove(); this._overlayLayers[this.currentLevel].remove(); L.DomUtil.removeClass(this._levelButtons[this.currentLevel], 'current'); } this._tileLayers[id].addTo(c3nav.map); this._overlayLayers[id].addTo(c3nav.map); L.DomUtil.addClass(this._levelButtons[id], 'current'); this.currentLevel = id; return true; }, _levelClick: function (e) { e.preventDefault(); e.stopPropagation(); this.setLevel(e.target.level); c3nav.update_map_state(); }, finalize: function () { var buttons = $(this._container).find('a'); buttons.addClass('current'); buttons.width(buttons.width()); buttons.removeClass('current'); } });
fix scroll wheel zoom on thinkpads and similar
src/c3nav/site/static/site/js/c3nav.js
fix scroll wheel zoom on thinkpads and similar
<ide><path>rc/c3nav/site/static/site/js/c3nav.js <ide> <ide> tile.style.width = tileSize.x + 1 + 'px'; <ide> tile.style.height = tileSize.y + 1 + 'px'; <add> } <add> }); <add> <add> /* <add> * Fix scroll wheel zoom on precise scrolling devices <add> */ <add> var originalPerformZoom = L.Map.ScrollWheelZoom.prototype._performZoom; <add> L.Map.ScrollWheelZoom.include({ <add> _performZoom: function () { <add> if (this._delta) this._delta = (this._delta > 0) ? Math.max(this._delta, 60) : Math.min(this._delta, -60); <add> originalPerformZoom.call(this); <ide> } <ide> }); <ide> }());
Java
apache-2.0
de5e80542f6a14e88ec25ce8e45ad7aaddd0b361
0
codescale/logging-log4j2,GFriedrich/logging-log4j2,ChetnaChaudhari/logging-log4j2,jsnikhil/nj-logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,neuro-sys/logging-log4j2,pisfly/logging-log4j2,xnslong/logging-log4j2,lburgazzoli/logging-log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,neuro-sys/logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,MagicWiz/log4j2,codescale/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/logging-log4j2,renchunxiao/logging-log4j2,lburgazzoli/apache-logging-log4j2,pisfly/logging-log4j2,apache/logging-log4j2,MagicWiz/log4j2,renchunxiao/logging-log4j2,lburgazzoli/logging-log4j2,jsnikhil/nj-logging-log4j2,jinxuan/logging-log4j2,ChetnaChaudhari/logging-log4j2,GFriedrich/logging-log4j2,jinxuan/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.log4j; /** * Provided for compatibility with Log4j 1.x. */ public class BasicConfigurator { protected BasicConfigurator() { } public static void configure() { LogManager.reconfigure(); } /** * No-op implementation. * @param appender The appender. */ public static void configure(final Appender appender) { // no-op } /** * No-op implementation. */ public static void resetConfiguration() { // no-op } }
log4j-1.2-api/src/main/java/org/apache/log4j/BasicConfigurator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.log4j; /** * Provided for compatibility with Log4j 1.x. */ public class BasicConfigurator { protected BasicConfigurator() { } public static void configure() { LogManager.reconfigure(); } /** * No-op implementation. * @param appender The appender. */ public static void configure(final Appender appender) { } /** * No-op implementation. */ public static void resetConfiguration() { } }
Document empty block.
log4j-1.2-api/src/main/java/org/apache/log4j/BasicConfigurator.java
Document empty block.
<ide><path>og4j-1.2-api/src/main/java/org/apache/log4j/BasicConfigurator.java <ide> * @param appender The appender. <ide> */ <ide> public static void configure(final Appender appender) { <add> // no-op <ide> } <ide> <ide> /** <ide> * No-op implementation. <ide> */ <ide> public static void resetConfiguration() { <add> // no-op <ide> } <ide> }
Java
agpl-3.0
3abe6009f78886812ebd3e5b4db4d1ae153e4a5e
0
roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.web.graph; public class PrefabGraph extends Object implements Comparable { private String m_name; private String m_title; private String[] m_columns; private String m_command; private String[] m_externalValues; private String[] m_propertiesValues; private int m_order; private String m_type; private String m_description; private String m_graphWidth; private String m_graphHeight; public PrefabGraph(String name, String title, String[] columns, String command, String[] externalValues, String[] propertiesValues, int order, String type, String description, String graphWidth, String graphHeight) { if (name == null || title == null || columns == null || command == null || externalValues == null) { throw new IllegalArgumentException("Cannot take null parameters."); } m_name = name; m_title = title; m_columns = columns; m_command = command; m_externalValues = externalValues; m_propertiesValues = propertiesValues; m_order = order; // type can be null m_type = type; // description can be null m_description = description; // width can be null m_graphWidth = graphWidth; // height can be null m_graphHeight = graphHeight; } public String getName() { return m_name; } public String getTitle() { return m_title; } public int getOrder() { return m_order; } public String[] getColumns() { return m_columns; } public String getCommand() { return m_command; } public String[] getExternalValues() { return m_externalValues; } public String[] getPropertiesValues() { return m_propertiesValues; } /** Can be null. */ public String getType() { return m_type; } /** Can be null. */ public String getDescription() { return m_description; } /** Can be null. */ public String getGraphWidth() { return m_graphWidth; } /** Can be null. */ public String getGraphHeight() { return m_graphHeight; } public int compareTo(Object obj) { if (obj == null) { throw new IllegalArgumentException("Cannot take null parameters."); } if (!(obj instanceof PrefabGraph)) { throw new IllegalArgumentException("Can only compare to PrefabGraph objects."); } PrefabGraph otherGraph = (PrefabGraph) obj; return getOrder() - otherGraph.getOrder(); } }
opennms-webapp/src/main/java/org/opennms/web/graph/PrefabGraph.java
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.web.graph; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.opennms.core.utils.BundleLists; public class PrefabGraph extends Object implements Comparable { private String m_name; private String m_title; private String[] m_columns; private String m_command; private String[] m_externalValues; private String[] m_propertiesValues; private int m_order; private String m_type; private String m_description; private String m_graphWidth; private String m_graphHeight; public PrefabGraph(String name, String title, String[] columns, String command, String[] externalValues, String[] propertiesValues, int order, String type, String description, String graphWidth, String graphHeight) { if (name == null || title == null || columns == null || command == null || externalValues == null) { throw new IllegalArgumentException("Cannot take null parameters."); } m_name = name; m_title = title; m_columns = columns; m_command = command; m_externalValues = externalValues; m_propertiesValues = propertiesValues; m_order = order; // type can be null m_type = type; // description can be null m_description = description; // width can be null m_graphWidth = graphWidth; // height can be null m_graphHeight = graphHeight; } public String getName() { return m_name; } public String getTitle() { return m_title; } public int getOrder() { return m_order; } public String[] getColumns() { return m_columns; } public String getCommand() { return m_command; } public String[] getExternalValues() { return m_externalValues; } public String[] getPropertiesValues() { return m_propertiesValues; } /** Can be null. */ public String getType() { return m_type; } /** Can be null. */ public String getDescription() { return m_description; } /** Can be null. */ public String getGraphWidth() { return m_graphWidth; } /** Can be null. */ public String getGraphHeight() { return m_graphHeight; } public int compareTo(Object obj) { if (obj == null) { throw new IllegalArgumentException("Cannot take null parameters."); } if (!(obj instanceof PrefabGraph)) { throw new IllegalArgumentException("Can only compare to PrefabGraph objects."); } PrefabGraph otherGraph = (PrefabGraph) obj; return getOrder() - otherGraph.getOrder(); } }
Remove unneedeed imports
opennms-webapp/src/main/java/org/opennms/web/graph/PrefabGraph.java
Remove unneedeed imports
<ide><path>pennms-webapp/src/main/java/org/opennms/web/graph/PrefabGraph.java <ide> // <ide> <ide> package org.opennms.web.graph; <del> <del>import java.util.HashMap; <del>import java.util.Map; <del>import java.util.Properties; <del> <del>import org.opennms.core.utils.BundleLists; <ide> <ide> public class PrefabGraph extends Object implements Comparable { <ide> private String m_name;
Java
mit
50f9c79a1ab835e63e39411016a88f5c79e439d6
0
BandUp/band-up-android
package com.melodies.bandup.MainScreenActivity; import android.content.Context; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.melodies.bandup.DatabaseSingleton; import com.melodies.bandup.R; import com.melodies.bandup.VolleySingleton; import com.melodies.bandup.helper_classes.User; import com.melodies.bandup.listeners.BandUpErrorListener; import com.melodies.bandup.listeners.BandUpResponseListener; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link UserListFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link UserListFragment#newInstance} factory method to * create an instance of this fragment. */ public class UserListFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public UserListFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment UserListFragment. */ // TODO: Rename and change types and number of parameters public static UserListFragment newInstance(String param1, String param2) { UserListFragment fragment = new UserListFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } private TextView txtName, txtDistance, txtInstruments, txtGenres, txtPercentage, txtAge; private View partialView; private ImageView ivUserProfileImage; UserListController ulc; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } ulc = new UserListController(); String url = getResources().getString(R.string.api_address).concat("/nearby-users"); DatabaseSingleton.getInstance(getActivity().getApplicationContext()).getBandUpDatabase().getUserList(new BandUpResponseListener() { @Override public void onBandUpResponse(Object response) { JSONArray responseArr = null; if (response instanceof JSONArray) { responseArr = (JSONArray) response; } else { return; } for (int i = 0; i < responseArr.length(); i++) { try { JSONObject item = responseArr.getJSONObject(i); User user = new User(); if (!item.isNull("_id")) user.id = item.getString("_id"); if (!item.isNull("username")) user.name = item.getString("username"); if (!item.isNull("status")) user.status = item.getString("status"); if (!item.isNull("distance")) user.distance = item.getInt("distance"); user.percentage = item.getInt("percentage"); if(!item.isNull("image")) { JSONObject userImg = item.getJSONObject("image"); if (!userImg.isNull("url")) { user.imgURL = userImg.getString("url"); } } JSONArray instrumentArray = item.getJSONArray("instruments"); for (int j = 0; j < instrumentArray.length(); j++) { user.instruments.add(instrumentArray.getString(j)); } JSONArray genreArray = item.getJSONArray("genres"); for (int j = 0; j < genreArray.length(); j++) { user.genres.add(genreArray.getString(j)); } ulc.addUser(user); } catch (JSONException e) { Toast.makeText(getActivity(), "Could not parse the JSON object.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } partialView.setVisibility(partialView.VISIBLE); if (ulc.users.size() > 0) { displayUser(ulc.getUser(0)); } } }, new BandUpErrorListener() { @Override public void onBandUpErrorResponse(VolleyError error) { VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_user_list, container, false); ivUserProfileImage = (ImageView) rootView.findViewById(R.id.imgProfile); txtName = (TextView) rootView.findViewById(R.id.txtName); txtInstruments = (TextView) rootView.findViewById(R.id.txtInstruments); txtGenres = (TextView) rootView.findViewById(R.id.txtGenres); txtDistance = (TextView) rootView.findViewById(R.id.txtDistance); txtPercentage = (TextView) rootView.findViewById(R.id.txtPercentage); txtAge = (TextView) rootView.findViewById(R.id.txtAge); txtName.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtInstruments.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtGenres.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtDistance.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtPercentage.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtAge.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); Button btnLike = (Button) rootView.findViewById(R.id.btnLike); Button btnDetails = (Button) rootView.findViewById(R.id.btnDetails); btnLike.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/master_of_break.ttf")); btnDetails.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/master_of_break.ttf")); partialView = rootView.findViewById(R.id.user_partial_view); return rootView; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public void onClickLike(View view) { JSONObject user = new JSONObject(); try { user.put("userID", ulc.getCurrentUser().id); } catch (JSONException e) { e.printStackTrace(); } String url = getActivity().getResources().getString(R.string.api_address).concat("/like"); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, url, user, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { Boolean isMatch = response.getBoolean("isMatch"); if (isMatch) { Toast.makeText(getActivity(), "You Matched!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "You liked this person", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); } } ); VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private void displayUser(User u) { txtName.setText(u.name); // Getting the first item for now. txtInstruments.setText(u.instruments.get(0)); txtGenres.setText(u.genres.get(0)); txtPercentage.setText(u.percentage + "%"); txtAge.setText(u.age+" years old"); txtDistance.setText(u.distance + " km away from you"); /*for (int i = 0; i < u.instruments.size(); i++) { if (i != u.instruments.size()-1) { txtInstruments.append(u.instruments.get(i) + ", "); } else { txtInstruments.append(u.instruments.get(i)); } }*/ Picasso.with(getActivity()).load(u.imgURL).into(ivUserProfileImage); } public void onClickNextUser(View view) { User u = ulc.getNextUser(); if (u == null) { return; } displayUser(u); } public void onClickPreviousUser(View view) { User u = ulc.getPrevUser(); if (u == null) { return; } displayUser(u); } }
app/src/main/java/com/melodies/bandup/MainScreenActivity/UserListFragment.java
package com.melodies.bandup.MainScreenActivity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.JsonObjectRequest; import com.melodies.bandup.DatabaseSingleton; import com.melodies.bandup.R; import com.melodies.bandup.VolleySingleton; import com.melodies.bandup.helper_classes.User; import com.melodies.bandup.listeners.BandUpErrorListener; import com.melodies.bandup.listeners.BandUpResponseListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link UserListFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link UserListFragment#newInstance} factory method to * create an instance of this fragment. */ public class UserListFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public UserListFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment UserListFragment. */ // TODO: Rename and change types and number of parameters public static UserListFragment newInstance(String param1, String param2) { UserListFragment fragment = new UserListFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } private TextView txtName, txtDistance, txtInstruments, txtGenres, txtPercentage, txtAge; private View partialView; private ImageView ivUserProfileImage; UserListController ulc; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } ulc = new UserListController(); String url = getResources().getString(R.string.api_address).concat("/nearby-users"); DatabaseSingleton.getInstance(getActivity().getApplicationContext()).getBandUpDatabase().getUserList(new BandUpResponseListener() { @Override public void onBandUpResponse(Object response) { JSONArray responseArr = null; if (response instanceof JSONArray) { responseArr = (JSONArray) response; } else { return; } for (int i = 0; i < responseArr.length(); i++) { try { JSONObject item = responseArr.getJSONObject(i); User user = new User(); if (!item.isNull("_id")) user.id = item.getString("_id"); if (!item.isNull("username")) user.name = item.getString("username"); if (!item.isNull("status")) user.status = item.getString("status"); if (!item.isNull("distance")) user.distance = item.getInt("distance"); user.percentage = item.getInt("percentage"); if(!item.isNull("image")) { JSONObject userImg = item.getJSONObject("image"); if (!userImg.isNull("url")) { user.imgURL = userImg.getString("url"); } } JSONArray instrumentArray = item.getJSONArray("instruments"); for (int j = 0; j < instrumentArray.length(); j++) { user.instruments.add(instrumentArray.getString(j)); } JSONArray genreArray = item.getJSONArray("genres"); for (int j = 0; j < genreArray.length(); j++) { user.genres.add(genreArray.getString(j)); } ulc.addUser(user); } catch (JSONException e) { Toast.makeText(getActivity(), "Could not parse the JSON object.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } partialView.setVisibility(partialView.VISIBLE); if (ulc.users.size() > 0) { displayUser(ulc.getUser(0)); } } }, new BandUpErrorListener() { @Override public void onBandUpErrorResponse(VolleyError error) { VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_user_list, container, false); ivUserProfileImage = (ImageView) rootView.findViewById(R.id.imgProfile); txtName = (TextView) rootView.findViewById(R.id.txtName); txtInstruments = (TextView) rootView.findViewById(R.id.txtInstruments); txtGenres = (TextView) rootView.findViewById(R.id.txtGenres); txtDistance = (TextView) rootView.findViewById(R.id.txtDistance); txtPercentage = (TextView) rootView.findViewById(R.id.txtPercentage); txtAge = (TextView) rootView.findViewById(R.id.txtAge); txtName.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtInstruments.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtGenres.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtDistance.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtPercentage.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); txtAge.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/caviar_dreams.ttf")); Button btnLike = (Button) rootView.findViewById(R.id.btnLike); Button btnDetails = (Button) rootView.findViewById(R.id.btnDetails); btnLike.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/master_of_break.ttf")); btnDetails.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/master_of_break.ttf")); partialView = rootView.findViewById(R.id.user_partial_view); return rootView; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public void onClickLike(View view) { JSONObject user = new JSONObject(); try { user.put("userID", ulc.getCurrentUser().id); } catch (JSONException e) { e.printStackTrace(); } String url = getActivity().getResources().getString(R.string.api_address).concat("/like"); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, url, user, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { Boolean isMatch = response.getBoolean("isMatch"); if (isMatch) { Toast.makeText(getActivity(), "You Matched!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "You liked this person", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); } } ); VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private void displayUser(User u) { txtName.setText(u.name); // Getting the first item for now. txtInstruments.setText(u.instruments.get(0)); txtGenres.setText(u.genres.get(0)); txtPercentage.setText(u.percentage + "%"); txtAge.setText(u.age+" years old"); txtDistance.setText(u.distance + " km away from you"); /*for (int i = 0; i < u.instruments.size(); i++) { if (i != u.instruments.size()-1) { txtInstruments.append(u.instruments.get(i) + ", "); } else { txtInstruments.append(u.instruments.get(i)); } }*/ ImageLoader il = VolleySingleton.getInstance(getActivity()).getImageLoader(); ivUserProfileImage.setImageResource(R.color.transparent); if (u.imgURL != null && !u.imgURL.equals("")) { il.get(u.imgURL, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { final Bitmap b = response.getBitmap(); if (b != null) { Runnable r = new Runnable() { @Override public void run() { ivUserProfileImage.setImageBitmap(b); } }; if (getActivity() != null) { getActivity().runOnUiThread(r); } } } @Override public void onErrorResponse(VolleyError error) { VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); } }); } } public void onClickNextUser(View view) { User u = ulc.getNextUser(); if (u == null) { return; } displayUser(u); } public void onClickPreviousUser(View view) { User u = ulc.getPrevUser(); if (u == null) { return; } displayUser(u); } }
Using Picasso to load images
app/src/main/java/com/melodies/bandup/MainScreenActivity/UserListFragment.java
Using Picasso to load images
<ide><path>pp/src/main/java/com/melodies/bandup/MainScreenActivity/UserListFragment.java <ide> package com.melodies.bandup.MainScreenActivity; <ide> <ide> import android.content.Context; <del>import android.graphics.Bitmap; <ide> import android.graphics.Typeface; <ide> import android.net.Uri; <ide> import android.os.Bundle; <ide> import com.android.volley.Request; <ide> import com.android.volley.Response; <ide> import com.android.volley.VolleyError; <del>import com.android.volley.toolbox.ImageLoader; <ide> import com.android.volley.toolbox.JsonObjectRequest; <ide> import com.melodies.bandup.DatabaseSingleton; <ide> import com.melodies.bandup.R; <ide> import com.melodies.bandup.helper_classes.User; <ide> import com.melodies.bandup.listeners.BandUpErrorListener; <ide> import com.melodies.bandup.listeners.BandUpResponseListener; <add>import com.squareup.picasso.Picasso; <ide> <ide> import org.json.JSONArray; <ide> import org.json.JSONException; <ide> } <ide> }*/ <ide> <del> ImageLoader il = VolleySingleton.getInstance(getActivity()).getImageLoader(); <del> ivUserProfileImage.setImageResource(R.color.transparent); <del> if (u.imgURL != null && !u.imgURL.equals("")) { <del> il.get(u.imgURL, new ImageLoader.ImageListener() { <del> @Override <del> public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { <del> final Bitmap b = response.getBitmap(); <del> if (b != null) { <del> Runnable r = new Runnable() { <del> @Override <del> public void run() { <del> ivUserProfileImage.setImageBitmap(b); <del> } <del> }; <del> if (getActivity() != null) { <del> getActivity().runOnUiThread(r); <del> } <del> } <del> } <del> <del> @Override <del> public void onErrorResponse(VolleyError error) { <del> VolleySingleton.getInstance(getActivity()).checkCauseOfError(error); <del> } <del> }); <del> } <add> Picasso.with(getActivity()).load(u.imgURL).into(ivUserProfileImage); <ide> } <ide> <ide> public void onClickNextUser(View view) {
Java
apache-2.0
58fb78fd9ab224f9754b9b9fcb61c2fcdb3bb668
0
zhoffice/redisson,redisson/redisson,ContaAzul/redisson,mrniko/redisson,jackygurui/redisson
/** * Copyright 2014 Nikita Koksharov, Nickolay Borbit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.connection; import io.netty.util.concurrent.Promise; import org.redisson.client.RedisClient; import org.redisson.client.RedisConnection; import org.redisson.client.protocol.RedisCommands; import org.redisson.core.ClusterNode; import java.net.InetSocketAddress; import java.util.Map; public class RedisClientEntry implements ClusterNode { private final RedisClient client; private final ConnectionManager manager; public RedisClientEntry(RedisClient client, ConnectionManager manager) { super(); this.client = client; this.manager = manager; } public RedisClient getClient() { return client; } @Override public InetSocketAddress getAddr() { return client.getAddr(); } private RedisConnection connect() { RedisConnection c = client.connect(); Promise<RedisConnection> future = manager.newPromise(); manager.getConnectListener().onConnect(future, c, null, manager.getConfig()); future.syncUninterruptibly(); return future.getNow(); } @Override public boolean ping() { RedisConnection c = null; try { c = connect(); return "PONG".equals(c.sync(RedisCommands.PING)); } catch (Exception e) { return false; } finally { if (c != null) { c.closeAsync(); } } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.getAddr().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RedisClientEntry other = (RedisClientEntry) obj; if (client == null) { if (other.client != null) return false; } else if (!client.getAddr().equals(other.client.getAddr())) return false; return true; } @Override public Map<String, String> info() { RedisConnection c = null; try { c = connect(); return c.sync(RedisCommands.CLUSTER_INFO); } catch (Exception e) { return null; } finally { if (c != null) { c.closeAsync(); } } } }
src/main/java/org/redisson/connection/RedisClientEntry.java
/** * Copyright 2014 Nikita Koksharov, Nickolay Borbit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.connection; import io.netty.util.concurrent.Promise; import org.redisson.client.RedisClient; import org.redisson.client.RedisConnection; import org.redisson.client.protocol.RedisCommands; import org.redisson.core.ClusterNode; import java.net.InetSocketAddress; import java.util.Map; public class RedisClientEntry implements ClusterNode { private final RedisClient client; private final ConnectionManager manager; public RedisClientEntry(RedisClient client, ConnectionManager manager) { super(); this.client = client; this.manager = manager; } public RedisClient getClient() { return client; } @Override public InetSocketAddress getAddr() { return client.getAddr(); } private RedisConnection connect() { RedisConnection c = client.connect(); Promise<RedisConnection> future = manager.newPromise(); manager.getConnectListener().onConnect(future, c, null, manager.getConfig()); future.syncUninterruptibly(); return future.getNow(); } @Override public boolean ping() { RedisConnection c = null; try { c = connect(); return "PONG".equals(c.sync(RedisCommands.PING)); } catch (Exception e) { return false; } finally { if (c != null) { c.closeAsync(); } } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.getAddr().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RedisClientEntry other = (RedisClientEntry) obj; if (client == null) { if (other.client != null) return false; } else if (!client.getAddr().equals(other.client.getAddr())) return false; return true; } @Override public Map<String, String> info() { RedisConnection c = connect(); try { return c.sync(RedisCommands.CLUSTER_INFO); } catch (Exception e) { return null; } finally { c.closeAsync(); } } }
ClusterNode.info fixed
src/main/java/org/redisson/connection/RedisClientEntry.java
ClusterNode.info fixed
<ide><path>rc/main/java/org/redisson/connection/RedisClientEntry.java <ide> <ide> @Override <ide> public Map<String, String> info() { <del> RedisConnection c = connect(); <add> RedisConnection c = null; <ide> try { <add> c = connect(); <ide> return c.sync(RedisCommands.CLUSTER_INFO); <ide> } catch (Exception e) { <ide> return null; <ide> } finally { <del> c.closeAsync(); <add> if (c != null) { <add> c.closeAsync(); <add> } <ide> } <ide> } <ide>
Java
apache-2.0
9a1240b88a9a2660847068a6c07c9a511da21350
0
danibusu/gateway,AdrianCozma/gateway,danibusu/gateway,danibusu/gateway,kaazing/gateway,jitsni/gateway,Anisotrop/gateway,stanculescu/gateway,Anisotrop/gateway,stanculescu/gateway,a-zuckut/gateway,jitsni/gateway,stanculescu/gateway,kaazing/gateway,Anisotrop/gateway,a-zuckut/gateway,jitsni/gateway,AdrianCozma/gateway,Anisotrop/gateway,kaazing/gateway,AdrianCozma/gateway,AdrianCozma/gateway,danibusu/gateway,stanculescu/gateway,a-zuckut/gateway,jitsni/gateway,kaazing/gateway,a-zuckut/gateway
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.gateway.update.check; import static java.util.concurrent.TimeUnit.DAYS; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductEdition; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductTitle; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductVersionPatch; import static org.kaazing.gateway.update.check.GatewayVersion.parseGatewayVersion; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import org.kaazing.gateway.server.GatewayObserverFactorySpi; import org.kaazing.gateway.server.context.GatewayContext; import org.kaazing.gateway.util.InternalSystemProperty; import org.kaazing.gateway.util.scheduler.SchedulerProvider; /** * Creates and manages periodic checks to see if the gateway has updates */ public class UpdateCheckGatewayObserver implements GatewayObserverFactorySpi { private static final String ENTERPRISE_URL = "https://version.kaazing.com"; private static final String COMMUNITY_URL = "https://version.kaazing.org"; private GatewayVersion currentVersion; private String productName; private String versionServiceUrl; private Set<UpdateCheckListener> listeners = new HashSet<>(); private GatewayVersion latestVersion; public UpdateCheckGatewayObserver() { addListener(new UpdateCheckLoggingListener()); } /** * @return latest @GatewayVersion or null if the latest version has not been discovered */ private synchronized GatewayVersion getLatestGatewayVersion() { return latestVersion; } protected void setLatestGatewayVersion(GatewayVersion newlatestVersion) { if (latestVersion != null && latestVersion.compareTo(newlatestVersion) >= 0) { return; } latestVersion = newlatestVersion; if (newlatestVersion.compareTo(currentVersion) <= 0) { return; } for (UpdateCheckListener listener : listeners) { listener.newVersionAvailable(currentVersion, getLatestGatewayVersion()); } } /** * Adds an @UpdateCheckListener who will be notified when the version changes, * @param newListener */ public void addListener(UpdateCheckListener newListener) { if (newListener == null) { throw new IllegalArgumentException("newListener"); } GatewayVersion latestGatewayVersion = getLatestGatewayVersion(); if (latestGatewayVersion != null && latestGatewayVersion.compareTo(currentVersion) > 0) { newListener.newVersionAvailable(currentVersion, latestGatewayVersion); } listeners.add(newListener); } @Override public void startingGateway(GatewayContext gatewayContext) { Map<String, Object> injectables = gatewayContext.getInjectables(); Properties properties = (Properties) injectables.get("configuration"); if (!InternalSystemProperty.UPDATE_CHECK.getBooleanProperty(properties)) { return; } productName = getGatewayProductTitle().replaceAll("\\s+", ""); currentVersion = parseGatewayVersion(getGatewayProductVersionPatch()); String serviceUrl = InternalSystemProperty.UPDATE_CHECK_SERVICE_URL.getProperty(properties); if (serviceUrl != null) { versionServiceUrl = serviceUrl; } else { versionServiceUrl = getGatewayProductEdition().toLowerCase().contains("enterprise") ? ENTERPRISE_URL : COMMUNITY_URL; } SchedulerProvider provider = (SchedulerProvider) injectables.get("schedulerProvider"); ScheduledExecutorService scheduler = provider.getScheduler("update_check", false); UpdateCheckTask updateCheckTask = new UpdateCheckTask(this, versionServiceUrl, productName); scheduler.scheduleAtFixedRate(updateCheckTask, 0, 7, DAYS); } }
update.check/src/main/java/org/kaazing/gateway/update/check/UpdateCheckGatewayObserver.java
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.gateway.update.check; import static java.util.concurrent.TimeUnit.DAYS; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductEdition; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductTitle; import static org.kaazing.gateway.server.impl.VersionUtils.getGatewayProductVersionPatch; import static org.kaazing.gateway.update.check.GatewayVersion.parseGatewayVersion; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import org.kaazing.gateway.server.GatewayObserverFactorySpi; import org.kaazing.gateway.server.context.GatewayContext; import org.kaazing.gateway.util.InternalSystemProperty; import org.kaazing.gateway.util.scheduler.SchedulerProvider; /** * Creates and manages periodic checks to see if the gateway has updates */ public class UpdateCheckGatewayObserver implements GatewayObserverFactorySpi { private static final String ENTERPRISE_URL = "https://version.kaazing.com"; private static final String COMMUNITY_URL = "https://version.kaazing.org"; private GatewayVersion currentVersion; private String productName; private String versionServiceUrl; private Set<UpdateCheckListener> listeners = new HashSet<>(); private GatewayVersion latestVersion; public UpdateCheckGatewayObserver() { addListener(new UpdateCheckLoggingListener()); } /** * @return latest @GatewayVersion or null if the latest version has not been discovered */ private synchronized GatewayVersion getLatestGatewayVersion() { return latestVersion; } protected void setLatestGatewayVersion(GatewayVersion newlatestVersion) { if (latestVersion != null && latestVersion.compareTo(newlatestVersion) >= 0) { return; } latestVersion = newlatestVersion; if (newlatestVersion.compareTo(currentVersion) <= 0) { return; } for (UpdateCheckListener listener : listeners) { listener.newVersionAvailable(currentVersion, getLatestGatewayVersion()); } } /** * Adds an @UpdateCheckListener who will be notified when the version changes, * @param newListener */ public void addListener(UpdateCheckListener newListener) { if (newListener == null) { throw new IllegalArgumentException("newListener"); } GatewayVersion latestGatewayVersion = getLatestGatewayVersion(); if (latestGatewayVersion != null && latestGatewayVersion.compareTo(currentVersion) > 0) { newListener.newVersionAvailable(currentVersion, latestGatewayVersion); } listeners.add(newListener); } @Override public void startingGateway(GatewayContext gatewayContext) { Map<String, Object> injectables = gatewayContext.getInjectables(); Properties properties = (Properties) injectables.get("configuration"); if (!InternalSystemProperty.UPDATE_CHECK.getBooleanProperty(properties)) { return; } productName = getGatewayProductTitle().replaceAll("\\s+", ""); currentVersion = parseGatewayVersion(getGatewayProductVersionPatch()); String serviceUrl = InternalSystemProperty.UPDATE_CHECK_SERVICE_URL.getProperty(properties); if (serviceUrl != null) { versionServiceUrl = serviceUrl; } else { versionServiceUrl = getGatewayProductEdition().toLowerCase().contains("enterprise") ? ENTERPRISE_URL : COMMUNITY_URL; } SchedulerProvider provider = (SchedulerProvider) injectables.get("schedulerProvider"); ScheduledExecutorService scheduler = provider.getScheduler("update_check", false); UpdateCheckTask updateCheckTask = new UpdateCheckTask(this, versionServiceUrl, productName); scheduler.scheduleAtFixedRate(updateCheckTask, 0, 7, DAYS); } }
Small formatting change
update.check/src/main/java/org/kaazing/gateway/update/check/UpdateCheckGatewayObserver.java
Small formatting change
<ide><path>pdate.check/src/main/java/org/kaazing/gateway/update/check/UpdateCheckGatewayObserver.java <ide> /** <ide> * Creates and manages periodic checks to see if the gateway has updates <ide> */ <del> public class UpdateCheckGatewayObserver implements GatewayObserverFactorySpi { <add>public class UpdateCheckGatewayObserver implements GatewayObserverFactorySpi { <ide> <ide> private static final String ENTERPRISE_URL = "https://version.kaazing.com"; <ide> private static final String COMMUNITY_URL = "https://version.kaazing.org"; <ide> if (serviceUrl != null) { <ide> versionServiceUrl = serviceUrl; <ide> } else { <del> versionServiceUrl = <del> getGatewayProductEdition().toLowerCase().contains("enterprise") ? ENTERPRISE_URL : COMMUNITY_URL; <add> versionServiceUrl = getGatewayProductEdition().toLowerCase().contains("enterprise") ? ENTERPRISE_URL : COMMUNITY_URL; <ide> } <ide> <ide> SchedulerProvider provider = (SchedulerProvider) injectables.get("schedulerProvider");
Java
apache-2.0
6d7cafb993fccb364473c1302cac776d06773648
0
google/ground-android,google/ground-android,google/ground-android
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.persistence.local; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.Matchers.samePropertyValuesAs; import androidx.arch.core.executor.testing.InstantTaskExecutorRule; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gnd.TestApplication; import com.google.android.gnd.inject.DaggerTestComponent; import com.google.android.gnd.model.Mutation; import com.google.android.gnd.model.Project; import com.google.android.gnd.model.User; import com.google.android.gnd.model.basemap.OfflineArea; import com.google.android.gnd.model.basemap.tile.Tile; import com.google.android.gnd.model.basemap.tile.Tile.State; import com.google.android.gnd.model.feature.Feature; import com.google.android.gnd.model.feature.FeatureMutation; import com.google.android.gnd.model.feature.Point; import com.google.android.gnd.model.form.Element; import com.google.android.gnd.model.form.Field; import com.google.android.gnd.model.form.Field.Type; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.form.MultipleChoice; import com.google.android.gnd.model.form.MultipleChoice.Cardinality; import com.google.android.gnd.model.form.Option; import com.google.android.gnd.model.layer.Layer; import com.google.android.gnd.model.layer.Style; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ObservationMutation; import com.google.android.gnd.model.observation.ResponseDelta; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.reactivex.subscribers.TestSubscriber; import java.util.AbstractCollection; import java.util.Date; import java8.util.Optional; import javax.inject.Inject; import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(application = TestApplication.class) public class LocalDataStoreTest { private static final User TEST_USER = User.builder().setId("user id").setEmail("[email protected]").setDisplayName("user 1").build(); private static final MultipleChoice TEST_MULTIPLE_CHOICE = MultipleChoice.newBuilder() .setCardinality(Cardinality.SELECT_ONE) .setOptions( ImmutableList.of( Option.newBuilder().setCode("a").setLabel("Name").build(), Option.newBuilder().setCode("b").setLabel("Age").build())) .build(); private static final Field TEST_FIELD = Field.newBuilder() .setId("field id") .setLabel("field label") .setRequired(false) .setType(Type.MULTIPLE_CHOICE) .setMultipleChoice(TEST_MULTIPLE_CHOICE) .build(); private static final Form TEST_FORM = Form.newBuilder() .setId("form id") .setElements(ImmutableList.of(Element.ofField(TEST_FIELD))) .build(); private static final Layer TEST_LAYER = Layer.newBuilder() .setId("layer id") .setItemLabel("item label") .setListHeading("heading title") .setDefaultStyle(Style.builder().setColor("000").build()) .setForm(TEST_FORM) .build(); private static final Project TEST_PROJECT = Project.newBuilder() .setId("project id") .setTitle("project 1") .setDescription("foo description") .putLayer("layer id", TEST_LAYER) .build(); private static final Point TEST_POINT = Point.newBuilder().setLatitude(110.0).setLongitude(-23.1).build(); private static final FeatureMutation TEST_FEATURE_MUTATION = FeatureMutation.builder() .setId(1L) .setFeatureId("feature id") .setType(Mutation.Type.CREATE) .setUserId("user id") .setProjectId("project id") .setLayerId("layer id") .setNewLocation(Optional.ofNullable(TEST_POINT)) .setClientTimestamp(new Date()) .build(); private static final ObservationMutation TEST_OBSERVATION_MUTATION = ObservationMutation.builder() .setObservationId("observation id") .setType(Mutation.Type.CREATE) .setProjectId("project id") .setFeatureId("feature id") .setLayerId("layer id") .setFormId("form id") .setUserId("user id") .setResponseDeltas( ImmutableList.of( ResponseDelta.builder() .setFieldId("field id") .setNewResponse(TextResponse.fromString("response for field id")) .build())) .setClientTimestamp(new Date()) .build(); private static final Tile TEST_PENDING_TILE = Tile.newBuilder() .setId("id_1") .setState(State.PENDING) .setPath("some_path 1") .setUrl("some_url 1") .build(); private static final Tile TEST_DOWNLOADED_TILE = Tile.newBuilder() .setId("id_2") .setState(State.DOWNLOADED) .setPath("some_path 2") .setUrl("some_url 2") .build(); private static final Tile TEST_FAILED_TILE = Tile.newBuilder() .setId("id_3") .setState(State.FAILED) .setPath("some_path 3") .setUrl("some_url 3") .build(); private static final OfflineArea TEST_OFFLINE_AREA = OfflineArea.newBuilder() .setId("id_1") .setBounds(LatLngBounds.builder().include(new LatLng(0.0, 0.0)).build()) .setState(OfflineArea.State.PENDING) .build(); // This rule makes sure that Room executes all the database operations instantly. @Rule public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule(); @Inject LocalDataStore localDataStore; private static void assertEqualsIgnoreId( ObservationMutation expected, ObservationMutation actual) { // TODO: Id is auto-assigned to ObservationMutation. // If we try to give it while inserting, then it causes problems. Improve this behavior. // So, copy the id from actual to expected and then compare the objects. expected = expected.toBuilder().setId(actual.getId()).build(); assertThat(expected).isEqualTo(actual); } private static void assertObservation(ObservationMutation mutation, Observation observation) { assertThat(mutation.getObservationId()).isEqualTo(observation.getId()); assertThat(mutation.getFeatureId()).isEqualTo(observation.getFeature().getId()); assertThat(TEST_USER).isEqualTo(observation.getCreated().getUser()); assertThat(TEST_FORM).isEqualTo(observation.getForm()); assertThat(TEST_PROJECT).isEqualTo(observation.getProject()); assertThat(TEST_USER).isEqualTo(observation.getLastModified().getUser()); MatcherAssert.assertThat( ResponseMap.builder().applyDeltas(mutation.getResponseDeltas()).build(), samePropertyValuesAs(observation.getResponses())); } private static void assertFeature(String featureId, Point point, Feature feature) { assertThat(featureId).isEqualTo(feature.getId()); assertThat(TEST_PROJECT).isEqualTo(feature.getProject()); assertThat(TEST_LAYER.getItemLabel()).isEqualTo(feature.getTitle()); assertThat(TEST_LAYER).isEqualTo(feature.getLayer()); assertThat(feature.getCustomId()).isNull(); assertThat(feature.getCaption()).isNull(); assertThat(point).isEqualTo(feature.getPoint()); assertThat(TEST_USER).isEqualTo(feature.getCreated().getUser()); assertThat(TEST_USER).isEqualTo(feature.getLastModified().getUser()); } @Before public void setUp() { DaggerTestComponent.create().inject(this); } @Test public void testGetProjects() { localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.getProjects().test().assertValue(ImmutableList.of(TEST_PROJECT)); } @Test public void testGetProjectById() { localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.getProjectById("project id").test().assertValue(TEST_PROJECT); } @Test public void testDeleteProject() { localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.deleteProject(TEST_PROJECT).test().assertComplete(); localDataStore.getProjects().test().assertValue(AbstractCollection::isEmpty); } @Test public void testGetUser() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.getUser("user id").test().assertValue(TEST_USER); } @Test public void testApplyAndEnqueue_featureMutation() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).test().assertComplete(); // assert that mutation is saved to local database localDataStore .getPendingMutations("feature id") .test() .assertValue(ImmutableList.of(TEST_FEATURE_MUTATION)); // assert feature is saved to local database Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); assertFeature("feature id", TEST_POINT, feature); } @Test public void testGetFeaturesOnceAndStream() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); TestSubscriber<ImmutableSet<Feature>> subscriber = localDataStore.getFeaturesOnceAndStream(TEST_PROJECT).test(); subscriber.assertValueCount(1); subscriber.assertValueAt(0, AbstractCollection::isEmpty); FeatureMutation mutation = TEST_FEATURE_MUTATION; localDataStore.applyAndEnqueue(mutation).blockingAwait(); Feature feature = localDataStore.getFeature(TEST_PROJECT, mutation.getFeatureId()).blockingGet(); subscriber.assertValueCount(2); subscriber.assertValueAt(0, AbstractCollection::isEmpty); subscriber.assertValueAt(1, ImmutableSet.of(feature)); } @Test public void testUpdateMutations() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); FeatureMutation mutation = TEST_FEATURE_MUTATION; localDataStore.applyAndEnqueue(mutation).blockingAwait(); Point newPoint = Point.newBuilder().setLatitude(51.0).setLongitude(44.0).build(); Mutation updatedMutation = mutation.toBuilder().setNewLocation(Optional.ofNullable(newPoint)).build(); localDataStore.updateMutations(ImmutableList.of(updatedMutation)).test().assertComplete(); ImmutableList<Mutation> savedMutations = localDataStore.getPendingMutations(updatedMutation.getFeatureId()).blockingGet(); assertThat(savedMutations).hasSize(1); FeatureMutation savedMutation = (FeatureMutation) savedMutations.get(0); assertThat(newPoint).isEqualTo(savedMutation.getNewLocation().get()); } @Test public void testRemovePendingMutation() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); localDataStore .removePendingMutations(ImmutableList.of(TEST_FEATURE_MUTATION)) .test() .assertComplete(); localDataStore .getPendingMutations("feature id") .test() .assertValue(AbstractCollection::isEmpty); } @Test public void testMergeFeature() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); Point point = Point.newBuilder().setLongitude(11.0).setLatitude(33.0).build(); feature = feature.toBuilder().setPoint(point).build(); localDataStore.mergeFeature(feature).test().assertComplete(); Feature newFeature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); assertFeature("feature id", point, newFeature); } @Test public void testApplyAndEnqueue_observationMutation() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).test().assertComplete(); ImmutableList<Mutation> savedMutations = localDataStore.getPendingMutations("feature id").blockingGet(); assertThat(savedMutations).hasSize(2); // ignoring the first item, which is a FeatureMutation. Already tested separately. assertEqualsIgnoreId(TEST_OBSERVATION_MUTATION, (ObservationMutation) savedMutations.get(1)); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); Observation observation = localDataStore.getObservation(feature, "observation id").blockingGet(); assertObservation(TEST_OBSERVATION_MUTATION, observation); // now update the inserted observation with new responses ImmutableList<ResponseDelta> deltas = ImmutableList.of( ResponseDelta.builder() .setFieldId("really new field") .setNewResponse(TextResponse.fromString("value for the really new field")) .build()); ObservationMutation mutation = TEST_OBSERVATION_MUTATION .toBuilder() .setResponseDeltas(deltas) .setType(Mutation.Type.UPDATE) .build(); localDataStore.applyAndEnqueue(mutation).test().assertComplete(); savedMutations = localDataStore.getPendingMutations("feature id").blockingGet(); assertThat(savedMutations).hasSize(3); // ignoring the first item, which is a FeatureMutation. Already tested separately. assertEqualsIgnoreId(mutation, (ObservationMutation) savedMutations.get(2)); // check if the observation was updated in the local database observation = localDataStore.getObservation(feature, "observation id").blockingGet(); assertObservation(mutation, observation); // also test that getObservations returns the same observation as well ImmutableList<Observation> observations = localDataStore.getObservations(feature, "form id").blockingGet(); assertThat(observations).hasSize(1); assertObservation(mutation, observations.get(0)); } @Test public void testMergeObservation() { localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).blockingAwait(); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); ResponseMap responseMap = ResponseMap.builder() .putResponse("foo field", TextResponse.fromString("foo value").get()) .build(); Observation observation = localDataStore .getObservation(feature, "observation id") .blockingGet() .toBuilder() .setResponses(responseMap) .build(); localDataStore.mergeObservation(observation).test().assertComplete(); ResponseMap responses = localDataStore .getObservation(feature, observation.getId()) .test() .values() .get(0) .getResponses(); assertThat("foo value").isEqualTo(responses.getResponse("foo field").get().toString()); } @Test public void testGetTile() { localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); localDataStore.getTile("id_1").test().assertValueCount(1).assertValue(TEST_PENDING_TILE); } @Test public void testGetTilesOnceAndStream() { TestSubscriber<ImmutableSet<Tile>> subscriber = localDataStore.getTilesOnceAndStream().test(); subscriber.assertValueCount(1); subscriber.assertValueAt(0, AbstractCollection::isEmpty); localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).blockingAwait(); localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); subscriber.assertValueCount(3); subscriber.assertValueAt(0, AbstractCollection::isEmpty); subscriber.assertValueAt(1, ImmutableSet.of(TEST_DOWNLOADED_TILE)); subscriber.assertValueAt(2, ImmutableSet.of(TEST_DOWNLOADED_TILE, TEST_PENDING_TILE)); } @Test public void testGetPendingTile() { localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).blockingAwait(); localDataStore.insertOrUpdateTile(TEST_FAILED_TILE).blockingAwait(); localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); localDataStore.getPendingTiles().test().assertValue(ImmutableList.of(TEST_PENDING_TILE)); } @Test public void testGetOfflineAreas() { localDataStore.insertOrUpdateOfflineArea(TEST_OFFLINE_AREA).blockingAwait(); localDataStore.getOfflineAreas().test().assertValue(ImmutableList.of(TEST_OFFLINE_AREA)); } }
gnd/src/test/java/com/google/android/gnd/persistence/local/LocalDataStoreTest.java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.persistence.local; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.Matchers.samePropertyValuesAs; import androidx.arch.core.executor.testing.InstantTaskExecutorRule; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gnd.TestApplication; import com.google.android.gnd.inject.DaggerTestComponent; import com.google.android.gnd.model.Mutation; import com.google.android.gnd.model.Project; import com.google.android.gnd.model.User; import com.google.android.gnd.model.basemap.OfflineArea; import com.google.android.gnd.model.basemap.tile.Tile; import com.google.android.gnd.model.basemap.tile.Tile.State; import com.google.android.gnd.model.feature.Feature; import com.google.android.gnd.model.feature.FeatureMutation; import com.google.android.gnd.model.feature.Point; import com.google.android.gnd.model.form.Element; import com.google.android.gnd.model.form.Field; import com.google.android.gnd.model.form.Field.Type; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.form.MultipleChoice; import com.google.android.gnd.model.form.MultipleChoice.Cardinality; import com.google.android.gnd.model.form.Option; import com.google.android.gnd.model.layer.Layer; import com.google.android.gnd.model.layer.Style; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ObservationMutation; import com.google.android.gnd.model.observation.ResponseDelta; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.reactivex.subscribers.TestSubscriber; import java.util.AbstractCollection; import java.util.Date; import java8.util.Optional; import javax.inject.Inject; import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(application = TestApplication.class) public class LocalDataStoreTest { private static final User TEST_USER = User.builder().setId("user id").setEmail("[email protected]").setDisplayName("user 1").build(); private static final MultipleChoice TEST_MULTIPLE_CHOICE = MultipleChoice.newBuilder() .setCardinality(Cardinality.SELECT_ONE) .setOptions( ImmutableList.of( Option.newBuilder().setCode("a").setLabel("Name").build(), Option.newBuilder().setCode("b").setLabel("Age").build())) .build(); private static final Field TEST_FIELD = Field.newBuilder() .setId("field id") .setLabel("field label") .setRequired(false) .setType(Type.MULTIPLE_CHOICE) .setMultipleChoice(TEST_MULTIPLE_CHOICE) .build(); private static final Form TEST_FORM = Form.newBuilder() .setId("form id") .setElements(ImmutableList.of(Element.ofField(TEST_FIELD))) .build(); private static final Layer TEST_LAYER = Layer.newBuilder() .setId("layer id") .setItemLabel("item label") .setListHeading("heading title") .setDefaultStyle(Style.builder().setColor("000").build()) .setForm(TEST_FORM) .build(); private static final Project TEST_PROJECT = Project.newBuilder() .setId("project id") .setTitle("project 1") .setDescription("foo description") .putLayer("layer id", TEST_LAYER) .build(); private static final Point TEST_POINT = Point.newBuilder().setLatitude(110.0).setLongitude(-23.1).build(); private static final FeatureMutation TEST_FEATURE_MUTATION = FeatureMutation.builder() .setId(1L) .setFeatureId("feature id") .setType(Mutation.Type.CREATE) .setUserId("user id") .setProjectId("project id") .setLayerId("layer id") .setNewLocation(Optional.ofNullable(TEST_POINT)) .setClientTimestamp(new Date()) .build(); private static final ObservationMutation TEST_OBSERVATION_MUTATION = ObservationMutation.builder() .setObservationId("observation id") .setType(Mutation.Type.CREATE) .setProjectId("project id") .setFeatureId("feature id") .setLayerId("layer id") .setFormId("form id") .setUserId("user id") .setResponseDeltas( ImmutableList.of( ResponseDelta.builder() .setFieldId("field id") .setNewResponse(TextResponse.fromString("response for field id")) .build())) .setClientTimestamp(new Date()) .build(); private static final Tile TEST_PENDING_TILE = Tile.newBuilder() .setId("id_1") .setState(State.PENDING) .setPath("some_path 1") .setUrl("some_url 1") .build(); private static final Tile TEST_DOWNLOADED_TILE = Tile.newBuilder() .setId("id_2") .setState(State.DOWNLOADED) .setPath("some_path 2") .setUrl("some_url 2") .build(); private static final Tile TEST_FAILED_TILE = Tile.newBuilder() .setId("id_3") .setState(State.FAILED) .setPath("some_path 3") .setUrl("some_url 3") .build(); private static final OfflineArea TEST_OFFLINE_AREA = OfflineArea.newBuilder() .setId("id_1") .setBounds(LatLngBounds.builder().include(new LatLng(0.0, 0.0)).build()) .setState(OfflineArea.State.PENDING) .build(); // This rule makes sure that Room executes all the database operations instantly. @Rule public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule(); @Inject LocalDataStore localDataStore; private static void assertEqualsIgnoreId( ObservationMutation expected, ObservationMutation actual) { // TODO: Id is auto-assigned to ObservationMutation. // If we try to give it while inserting, then it causes problems. Improve this behavior. // So, copy the id from actual to expected and then compare the objects. expected = expected.toBuilder().setId(actual.getId()).build(); assertThat(expected).isEqualTo(actual); } private static void assertObservation(ObservationMutation mutation, Observation observation) { assertThat(mutation.getObservationId()).isEqualTo(observation.getId()); assertThat(mutation.getFeatureId()).isEqualTo(observation.getFeature().getId()); assertThat(TEST_USER).isEqualTo(observation.getCreated().getUser()); assertThat(TEST_FORM).isEqualTo(observation.getForm()); assertThat(TEST_PROJECT).isEqualTo(observation.getProject()); assertThat(TEST_USER).isEqualTo(observation.getLastModified().getUser()); MatcherAssert.assertThat( ResponseMap.builder().applyDeltas(mutation.getResponseDeltas()).build(), samePropertyValuesAs(observation.getResponses())); } private static void assertFeature(String featureId, Point point, Feature feature) { assertThat(featureId).isEqualTo(feature.getId()); assertThat(TEST_PROJECT).isEqualTo(feature.getProject()); assertThat(TEST_LAYER.getItemLabel()).isEqualTo(feature.getTitle()); assertThat(TEST_LAYER).isEqualTo(feature.getLayer()); assertThat(feature.getCustomId()).isNull(); assertThat(feature.getCaption()).isNull(); assertThat(point).isEqualTo(feature.getPoint()); assertThat(TEST_USER).isEqualTo(feature.getCreated().getUser()); assertThat(TEST_USER).isEqualTo(feature.getLastModified().getUser()); } @Before public void setUp() { DaggerTestComponent.create().inject(this); } @Test public void testGetProjects() { localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.getProjects().test().assertValue(ImmutableList.of(TEST_PROJECT)); } @Test public void testGetProjectById() { localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.getProjectById("project id").test().assertValue(TEST_PROJECT); } @Test public void testDeleteProject() { localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.deleteProject(TEST_PROJECT).test().assertComplete(); localDataStore.getProjects().test().assertValue(AbstractCollection::isEmpty); } @Test public void testGetUser() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.getUser("user id").test().assertValue(TEST_USER); } @Test public void testApplyAndEnqueue_featureMutation() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).test().assertComplete(); // assert that mutation is saved to local database localDataStore .getPendingMutations("feature id") .test() .assertValue(ImmutableList.of(TEST_FEATURE_MUTATION)); // assert feature is saved to local database Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); assertFeature("feature id", TEST_POINT, feature); } @Test public void testGetFeaturesOnceAndStream() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); TestSubscriber<ImmutableSet<Feature>> subscriber = localDataStore.getFeaturesOnceAndStream(TEST_PROJECT).test(); subscriber.assertValueCount(1); subscriber.assertValueAt(0, AbstractCollection::isEmpty); FeatureMutation mutation = TEST_FEATURE_MUTATION; localDataStore.applyAndEnqueue(mutation).subscribe(); Feature feature = localDataStore.getFeature(TEST_PROJECT, mutation.getFeatureId()).blockingGet(); subscriber.assertValueCount(2); subscriber.assertValueAt(0, AbstractCollection::isEmpty); subscriber.assertValueAt(1, ImmutableSet.of(feature)); } @Test public void testUpdateMutations() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); FeatureMutation mutation = TEST_FEATURE_MUTATION; localDataStore.applyAndEnqueue(mutation).subscribe(); Point newPoint = Point.newBuilder().setLatitude(51.0).setLongitude(44.0).build(); Mutation updatedMutation = mutation.toBuilder().setNewLocation(Optional.ofNullable(newPoint)).build(); localDataStore.updateMutations(ImmutableList.of(updatedMutation)).test().assertComplete(); ImmutableList<Mutation> savedMutations = localDataStore.getPendingMutations(updatedMutation.getFeatureId()).blockingGet(); assertThat(savedMutations).hasSize(1); FeatureMutation savedMutation = (FeatureMutation) savedMutations.get(0); assertThat(newPoint).isEqualTo(savedMutation.getNewLocation().get()); } @Test public void testRemovePendingMutation() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); localDataStore .removePendingMutations(ImmutableList.of(TEST_FEATURE_MUTATION)) .test() .assertComplete(); localDataStore .getPendingMutations("feature id") .test() .assertValue(AbstractCollection::isEmpty); } @Test public void testMergeFeature() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); Point point = Point.newBuilder().setLongitude(11.0).setLatitude(33.0).build(); feature = feature.toBuilder().setPoint(point).build(); localDataStore.mergeFeature(feature).test().assertComplete(); Feature newFeature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); assertFeature("feature id", point, newFeature); } @Test public void testApplyAndEnqueue_observationMutation() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).test().assertComplete(); ImmutableList<Mutation> savedMutations = localDataStore.getPendingMutations("feature id").blockingGet(); assertThat(savedMutations).hasSize(2); // ignoring the first item, which is a FeatureMutation. Already tested separately. assertEqualsIgnoreId(TEST_OBSERVATION_MUTATION, (ObservationMutation) savedMutations.get(1)); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); Observation observation = localDataStore.getObservation(feature, "observation id").blockingGet(); assertObservation(TEST_OBSERVATION_MUTATION, observation); // now update the inserted observation with new responses ImmutableList<ResponseDelta> deltas = ImmutableList.of( ResponseDelta.builder() .setFieldId("really new field") .setNewResponse(TextResponse.fromString("value for the really new field")) .build()); ObservationMutation mutation = TEST_OBSERVATION_MUTATION .toBuilder() .setResponseDeltas(deltas) .setType(Mutation.Type.UPDATE) .build(); localDataStore.applyAndEnqueue(mutation).test().assertComplete(); savedMutations = localDataStore.getPendingMutations("feature id").blockingGet(); assertThat(savedMutations).hasSize(3); // ignoring the first item, which is a FeatureMutation. Already tested separately. assertEqualsIgnoreId(mutation, (ObservationMutation) savedMutations.get(2)); // check if the observation was updated in the local database observation = localDataStore.getObservation(feature, "observation id").blockingGet(); assertObservation(mutation, observation); // also test that getObservations returns the same observation as well ImmutableList<Observation> observations = localDataStore.getObservations(feature, "form id").blockingGet(); assertThat(observations).hasSize(1); assertObservation(mutation, observations.get(0)); } @Test public void testMergeObservation() { localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).subscribe(); Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); ResponseMap responseMap = ResponseMap.builder() .putResponse("foo field", TextResponse.fromString("foo value").get()) .build(); Observation observation = localDataStore .getObservation(feature, "observation id") .blockingGet() .toBuilder() .setResponses(responseMap) .build(); localDataStore.mergeObservation(observation).test().assertComplete(); ResponseMap responses = localDataStore .getObservation(feature, observation.getId()) .test() .values() .get(0) .getResponses(); assertThat("foo value").isEqualTo(responses.getResponse("foo field").get().toString()); } @Test public void testGetTile() { localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); localDataStore.getTile("id_1").test().assertValueCount(1).assertValue(TEST_PENDING_TILE); } @Test public void testGetTilesOnceAndStream() { TestSubscriber<ImmutableSet<Tile>> subscriber = localDataStore.getTilesOnceAndStream().test(); subscriber.assertValueCount(1); subscriber.assertValueAt(0, AbstractCollection::isEmpty); localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).subscribe(); localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); subscriber.assertValueCount(3); subscriber.assertValueAt(0, AbstractCollection::isEmpty); subscriber.assertValueAt(1, ImmutableSet.of(TEST_DOWNLOADED_TILE)); subscriber.assertValueAt(2, ImmutableSet.of(TEST_DOWNLOADED_TILE, TEST_PENDING_TILE)); } @Test public void testGetPendingTile() { localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).subscribe(); localDataStore.insertOrUpdateTile(TEST_FAILED_TILE).subscribe(); localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); localDataStore.getPendingTiles().test().assertValue(ImmutableList.of(TEST_PENDING_TILE)); } @Test public void testGetOfflineAreas() { localDataStore.insertOrUpdateOfflineArea(TEST_OFFLINE_AREA).subscribe(); localDataStore.getOfflineAreas().test().assertValue(ImmutableList.of(TEST_OFFLINE_AREA)); } }
Replace subscribe by blockingAwait
gnd/src/test/java/com/google/android/gnd/persistence/local/LocalDataStoreTest.java
Replace subscribe by blockingAwait
<ide><path>nd/src/test/java/com/google/android/gnd/persistence/local/LocalDataStoreTest.java <ide> <ide> @Test <ide> public void testGetProjects() { <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> localDataStore.getProjects().test().assertValue(ImmutableList.of(TEST_PROJECT)); <ide> } <ide> <ide> @Test <ide> public void testGetProjectById() { <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> localDataStore.getProjectById("project id").test().assertValue(TEST_PROJECT); <ide> } <ide> <ide> @Test <ide> public void testDeleteProject() { <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> localDataStore.deleteProject(TEST_PROJECT).test().assertComplete(); <ide> localDataStore.getProjects().test().assertValue(AbstractCollection::isEmpty); <ide> } <ide> <ide> @Test <ide> public void testGetUser() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <ide> localDataStore.getUser("user id").test().assertValue(TEST_USER); <ide> } <ide> <ide> @Test <ide> public void testApplyAndEnqueue_featureMutation() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> <ide> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).test().assertComplete(); <ide> <ide> <ide> @Test <ide> public void testGetFeaturesOnceAndStream() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> <ide> TestSubscriber<ImmutableSet<Feature>> subscriber = <ide> localDataStore.getFeaturesOnceAndStream(TEST_PROJECT).test(); <ide> subscriber.assertValueAt(0, AbstractCollection::isEmpty); <ide> <ide> FeatureMutation mutation = TEST_FEATURE_MUTATION; <del> localDataStore.applyAndEnqueue(mutation).subscribe(); <add> localDataStore.applyAndEnqueue(mutation).blockingAwait(); <ide> <ide> Feature feature = <ide> localDataStore.getFeature(TEST_PROJECT, mutation.getFeatureId()).blockingGet(); <ide> <ide> @Test <ide> public void testUpdateMutations() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <ide> <ide> FeatureMutation mutation = TEST_FEATURE_MUTATION; <del> localDataStore.applyAndEnqueue(mutation).subscribe(); <add> localDataStore.applyAndEnqueue(mutation).blockingAwait(); <ide> <ide> Point newPoint = Point.newBuilder().setLatitude(51.0).setLongitude(44.0).build(); <ide> Mutation updatedMutation = <ide> <ide> @Test <ide> public void testRemovePendingMutation() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <del> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <add> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); <ide> <ide> localDataStore <ide> .removePendingMutations(ImmutableList.of(TEST_FEATURE_MUTATION)) <ide> <ide> @Test <ide> public void testMergeFeature() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <del> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <add> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); <ide> <ide> Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); <ide> Point point = Point.newBuilder().setLongitude(11.0).setLatitude(33.0).build(); <ide> <ide> @Test <ide> public void testApplyAndEnqueue_observationMutation() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <del> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <add> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); <ide> <ide> localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).test().assertComplete(); <ide> <ide> <ide> @Test <ide> public void testMergeObservation() { <del> localDataStore.insertOrUpdateUser(TEST_USER).subscribe(); <del> localDataStore.insertOrUpdateProject(TEST_PROJECT).subscribe(); <del> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).subscribe(); <del> localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).subscribe(); <add> localDataStore.insertOrUpdateUser(TEST_USER).blockingAwait(); <add> localDataStore.insertOrUpdateProject(TEST_PROJECT).blockingAwait(); <add> localDataStore.applyAndEnqueue(TEST_FEATURE_MUTATION).blockingAwait(); <add> localDataStore.applyAndEnqueue(TEST_OBSERVATION_MUTATION).blockingAwait(); <ide> Feature feature = localDataStore.getFeature(TEST_PROJECT, "feature id").blockingGet(); <ide> <ide> ResponseMap responseMap = <ide> <ide> @Test <ide> public void testGetTile() { <del> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); <add> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); <ide> localDataStore.getTile("id_1").test().assertValueCount(1).assertValue(TEST_PENDING_TILE); <ide> } <ide> <ide> subscriber.assertValueCount(1); <ide> subscriber.assertValueAt(0, AbstractCollection::isEmpty); <ide> <del> localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).subscribe(); <del> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); <add> localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).blockingAwait(); <add> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); <ide> <ide> subscriber.assertValueCount(3); <ide> subscriber.assertValueAt(0, AbstractCollection::isEmpty); <ide> <ide> @Test <ide> public void testGetPendingTile() { <del> localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).subscribe(); <del> localDataStore.insertOrUpdateTile(TEST_FAILED_TILE).subscribe(); <del> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).subscribe(); <add> localDataStore.insertOrUpdateTile(TEST_DOWNLOADED_TILE).blockingAwait(); <add> localDataStore.insertOrUpdateTile(TEST_FAILED_TILE).blockingAwait(); <add> localDataStore.insertOrUpdateTile(TEST_PENDING_TILE).blockingAwait(); <ide> localDataStore.getPendingTiles().test().assertValue(ImmutableList.of(TEST_PENDING_TILE)); <ide> } <ide> <ide> @Test <ide> public void testGetOfflineAreas() { <del> localDataStore.insertOrUpdateOfflineArea(TEST_OFFLINE_AREA).subscribe(); <add> localDataStore.insertOrUpdateOfflineArea(TEST_OFFLINE_AREA).blockingAwait(); <ide> localDataStore.getOfflineAreas().test().assertValue(ImmutableList.of(TEST_OFFLINE_AREA)); <ide> } <ide> }
JavaScript
mit
2d534d6ec45f6838ec314820984c697f44bfe19f
0
ryanoshea/poll-princeton,ryanoshea/poll-princeton
var http = require('http'); var https = require('https'); var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var crypto = require('crypto'); var async = require('async'); var fs = require('fs'); var app = express(); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data /* MongoDB Setup */ var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test-pp'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (callback) { console.log('mongoose: Connected to database \'test-pp\''); }); /* Collections */ var pollSchema = mongoose.Schema({ question: String, choices: [String], responses: [Number], author: String, time: Date, pid: String, upvotes: Number, downvotes: Number, score: Number }); var Poll = mongoose.model('Poll', pollSchema); var ticketSchema = mongoose.Schema({ netid: String, ticket: String }); var Ticket = mongoose.model('Ticket', ticketSchema); var userLogSchema = mongoose.Schema({ netid: String, time: Date }); var userLog = mongoose.model('userLog', userLogSchema); var voteSchema = mongoose.Schema({ netid: String, pid: String, upOrDown: Boolean //true is up }); var Vote = mongoose.model('Vote', voteSchema); var responseSchema = mongoose.Schema({ netid: String, pid: String, idx: Number //true is up }); var Response = mongoose.model('Response', responseSchema); var studentSchema = mongoose.Schema({ first: String, last: String, netid: String, 'class': String, home: String, major: String, dorm: String, rescol: String }); var Student = mongoose.model('Student', studentSchema); /* REST Handlers */ app.post('/polls/submit', function (req, res) { console.log('POST request for /polls/submit/'); //res.json(req.body); // parse request body, populate req.body object console.log(req.body); var newPoll = {}; newPoll.question = req.body.question; newPoll.choices = req.body.choices; newPoll.responses = []; for (var i in newPoll.choices) newPoll.responses.push(0); newPoll.author = req.body.author; newPoll.upvotes = 0; newPoll.downvotes = 0; newPoll.score = 0; var sha256 = crypto.createHash('sha256'); sha256.update(newPoll.question + newPoll.author); newPoll.pid = sha256.digest('hex'); newPoll.time = new Date(); var question = new Poll(newPoll); question.save(function (err) { if (err) return console.error(err); }); res.send({'pid' : newPoll.pid}); }); /* app.get('/polls/get/all', function (req, res) { console.log('GET request for /polls/get/all'); Poll.find({}, 'question choices time pid score', function (err, polls) { res.send(polls); }); }); */ app.get('/polls/get/:sortType/:netid/:num/:onlyUser', function(req, res) { console.log('GET request for /polls/' + req.params.sortType + '/' + req.params.netid + '/' + req.params.num); var user = req.params.netid; var current = req.params.num; var onlyUser = req.params.onlyUser; var sortBy; var fields; if (req.params.sortType == 'popular') sortBy = {'score': -1}; else if (req.params.sortType == 'newest') sortBy = {time: -1}; if (req.params.onlyUser == 'true') fields = {'author': user}; else if (req.params.onlyUser == 'false') fields = {}; Poll.find(fields).sort(sortBy).skip(current).limit(10).exec(function (err, polls) { var ret = []; async.eachSeries(polls, function(p, callback) { //console.log("date at start of loop: " + p.time); var pid = p.pid; var userVote; var userResponse; Vote.findOne({'pid' : pid, 'netid' : user}, function (err, vote) { //console.log(vote); if (vote != null) { //console.log('test'); userVote = vote.upOrDown; } else { userVote = null; } Response.findOne({pid: pid, netid: user}, function (err, response) { if (err) console.log('Error.'); if (response == null) userResponse = -1; else userResponse = response.idx; var newPollData = { pollData: p, userVote: userVote, userResponse: userResponse, isAuthor: p.author == user }; //console.log("time added into ret: " + newPollData.pollData.time); ret.push(newPollData); //console.log(ret.length); callback(); }) }); }, function(err) { if (err) console.log('Error.'); else { //console.log(polls.length + " " + ret.length); if (ret.length === 0) { res.send({err: true}); } else res.send(ret); } }); }); }); app.get('/polls/get/:pid/:netid', function(req, res) { console.log('GET request for /polls/get/' + req.params.pid + '/' + req.params.netid); Poll.findOne({'pid' : req.params.pid}, 'question choices responses time pid score author', function (err, poll) { if (err) console.log('Error.'); if (poll == null) res.send({'err': true, 'question': 'This poll does not exist.'}); else { var ret = {}; ret.question = poll.question; ret.choices = poll.choices; ret.responses = poll.responses; ret.time = poll.time; ret.pid = poll.pid; ret.score = poll.score; ret.isAuthor = poll.author === req.params.netid; Vote.findOne({'pid' : req.params.pid, 'netid' : req.params.netid}, function (err, vote) { //console.log(vote); if (vote != null) { console.log('test'); ret.userVote = vote.upOrDown; } else { ret.userVote = null; } Response.findOne({pid: req.params.pid, netid: req.params.netid}, function (err, response) { if (err) console.log('Error.'); if (response == null) ret.userResponse = -1; else ret.userResponse = response.idx; console.log(ret); res.send(ret); }) }); } }); }); // This + the get function above. Authentication? app.get('/polls/get/:netid', function(req, res) { var user = req.params.netid; console.log('GET request for /polls/get/' + user); Poll.find({"author": user}, 'question choices time pid score', function (err, polls) { res.send(polls); }); }); app.delete('/polls/delete/:pid/:netid/:ticket', function(req, res) { console.log('DELETE request for poll: ' + req.params.pid + ' by user: ' + req.params.netid); var pid = req.params.pid; var netid = req.params.netid; var ticket = req.params.ticket; Poll.findOne({pid: pid}, 'author', function (err, poll) { if (err) { console.log('Database error.'); res.send({err: true, msg: 'Database error.'}); return; } else if (poll == null) { console.log('Poll not found.'); res.send({err: true, msg: 'No poll with that ID found.'}); return; } else if (poll.author !== netid && netid !== 'roshea' && netid !== 'marchant' && netid != 'hzlu') { console.log('Non-author, non-admin tried to delete poll. Cancelling.'); res.send({err: true, msg: 'You are not the author of the given poll, so you can\'t delete it.'}); return; } else { Poll.findOneAndRemove({pid: pid}, function (err, poll) { Response.remove({pid: pid}, function (err) { Vote.remove({pid: pid}, function (err) { res.send({err: false}); }); }); }); } }); }); /* app.get('/polls/delete/all', function (req, res) { console.log('GET request for /polls/delete/all'); Poll.find({}).remove().exec(); Vote.find({}).remove().exec(); res.end(); }); */ // Plus send pid. app.post('/polls/vote', function (req, res) { console.log('POST request for /polls/vote'); //res.json(req.body); // parse request body, populate req.body object console.log(req.body); upOrDown = req.body.upOrDown; // up is true pollID = req.body.pollID; netid = req.body.netid; var reversed = false; var negated = false; if (netid !== null) { Vote.findOne({'pid' : pollID, 'netid' : netid}, 'upOrDown', function (err, oldVote) { if (err) console.log('Error with vote db.'); if (oldVote) { var oldUpOrDown = oldVote.upOrDown; console.log("new " + upOrDown); console.log("old " + oldUpOrDown); if (upOrDown == oldUpOrDown) { console.log("removing " + pollID + " " + netid); var conditions = {pid: pollID, netid: netid}; Vote.findOneAndRemove(conditions, function (err, results) { console.log("remove results: " + results); //** These two not guaranteed to execute in order }); //if already voted button pressed again negated = true; } else { var conditions = {pid: pollID, netid: netid}; var update = {upOrDown: upOrDown}; Vote.findOneAndUpdate(conditions, update, function (err, results) { console.log("updated results: " + results); //** Need to be made sync? }); //if other button pressed reversed = true; } } else { var newVoteFields = {}; newVoteFields.netid = netid; newVoteFields.upOrDown = upOrDown; newVoteFields.pid = pollID; var newVote = new Vote(newVoteFields); newVote.save(function (err) { if (err) return console.error(err); //if no button pressed yet }); } var conditions = {pid: pollID}; var update; console.log("negated " + negated); // This clusterfuck if (upOrDown) { if (reversed) { update = {$inc: {upvotes:1, downvotes: -1, score:2}}; } else if (negated) { update = {$inc: {upvotes:-1, score:-1}}; } else { update = {$inc: {upvotes:1, score:1}}; } } else { if (reversed) { update = {$inc: {downvotes:1, upvotes: -1, score:-2}}; } else if (negated) { update = {$inc: {downvotes:-1, score:1}}; } else { update = {$inc: {downvotes:1, score:-1}}; } } var options = {new: true}; Poll.findOneAndUpdate(conditions, update, options, function (err, updatedPoll) { console.log('New score: ' + updatedPoll); if (err) console.log('Error.'); if (updatedPoll == null) res.send({'err': true, 'question': 'This poll does not exist.'}); else { var ret = {}; ret.question = updatedPoll.question; ret.score = updatedPoll.score; ret.choices = updatedPoll.choices; ret.responses = updatedPoll.responses; ret.pid = updatedPoll.pid; if (negated) ret.userVote = null; else { ret.userVote = upOrDown; } res.send(ret); } }); }); } else { res.send({'err': true, 'netid': 'You are not logged in.'}); } }); /* Logs a user response to a poll. Returns the updated responses array for the poll. */ app.post('/polls/respond', function (req, res) { //res.json(req.body); // parse request body, populate req.body object console.log('POST request for /polls/respond'); console.log('Request contents: ' + req.body); var netid = req.body.netid; var pid = req.body.pid; var idx = req.body.idx; if (netid !== null) { Response.findOne({'netid': netid, 'pid': pid}, function (err, response) { if (err) console.log('Error.'); else if (response == null) { // Create new response object, update poll with new score for the right choice console.log('User ' + netid + ' has not responded to poll ' + pid + ' before. Creating new response.'); var newResp = {}; newResp.netid = netid; newResp.pid = pid; newResp.idx = idx; var entry = new Response(newResp); entry.save(function (err) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + idx] = 1; Poll.findOneAndUpdate({pid: pid}, update, function (err, poll) { if (err) { console.error(err); res.send({err: true}); } Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: idx}); } }); }); } }); } else { if (response.idx === idx) { // Revoke response console.log('User ' + netid + ' unselected their response to ' + pid + '. Revoking response.'); Response.findOneAndRemove({'netid': netid, 'pid': pid}, function (err, response) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + idx] = -1; Poll.findOneAndUpdate({pid: pid}, update, function (err, poll) { if (err) { console.error(err); res.send({err: true}); } else { Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: -1}); } }); } }); } }); } else { // Update response console.log('User ' + netid + ' has changed their response to ' + pid + '. Updating response.'); var update = {$set: {idx: idx}}; Response.findOneAndUpdate({pid: pid, netid: netid}, update, function (err, newResponse) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + response.idx] = -1; update.$inc['responses.' + idx] = 1; Poll.findOneAndUpdate({pid: pid}, update, function (err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else { Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: idx}); } }); } }); } }); } } }); } }); // Indicates whether the provided CAS ticket (for just-after-login) or ticket/netid pair (for return // visits) are valid, and thus the user is logged in. Returns {loggedin : true/false}. app.post('/auth/loggedin', function (req, res) { console.log('POST request for /auth/loggedin'); // Check for the ticket in the db of currently-logged-in tickets/users var foundInDB = false; var sentTicket = {ticket: req.body.ticket, netid: req.body.netid}; Ticket.findOne({ticket: sentTicket.ticket}, function (err, ticket) { if (ticket != null) { // The user is already logged in console.log("Found user " + ticket.netid + " in database. Authenticated."); foundInDB = true; // Query for user's Full Name var fullname = ""; //Logging visitors var newLogDate = new Date(); var log = ticket.netid + " " + newLogDate + '\n'; var newUserLog = {netid: ticket.netid, time: newLogDate}; var saveLog = new userLog(newUserLog); userLog.findOne({netid: ticket.netid}, function(err, result) { if (result == null) { saveLog.save(function (err) { console.log("saving unique user"); if (err) console.log("Database log save error."); }); } }); fs.appendFile('userLog.txt', log, function (err) { if (err) console.log('Logging error'); }); Student.findOne({'netid': ticket.netid}, function (err, student) { if (err) console.log('Student db error'); if (student !== null) { fullname = student.first + ' ' + student.last; } res.send({'loggedin' : true, 'netid' : ticket.netid, 'fullname': fullname}); }); } else { // User not found in db; check with CAS's validation server console.log("Could not find user " + sentTicket.netid + " in database."); var casValidateUrl = 'https://fed.princeton.edu/cas/validate?ticket=' + req.body.ticket + '&service=' + req.body.returnUrl; console.log('Querying ' + casValidateUrl); var response = ""; https.get(casValidateUrl, function(resp) { resp.on('data', function(d) { // Piece chunks of response together response = response + d; }); resp.on('end', function(d) { // Response is ready, continue console.log('Response from CAS: ' + response); if (response.charAt(0) == 'y') { // CAS approved the ticket var netid = response.substring(response.indexOf('\n') + 1, response.length - 1); //Logging visitors var newLogDate = new Date(); var log = netid + " " + newLogDate + '\n'; var newUserLog = {netid: netid, time: newLogDate}; var saveLog = new userLog(newUserLog); userLog.findOne({netid: netid}, function(err, result) { if (result == null) { saveLog.save(function (err) { if (err) console.log("Database log save error."); }); } }); fs.appendFile('userLog.txt', log, function (err) { if (err) console.log('Logging error'); }); //Save ticket var newTicket = {ticket: req.body.ticket, netid: netid}; console.log(newTicket); var saveTicket = new Ticket(newTicket); saveTicket.save(function (err) { if (err) console.log("Database ticket save error."); }); // Query for user's Full Name var fullname = ""; Student.findOne({'netid': netid}, function (err, student) { if (err) console.log('Student db error'); if (student !== null) { fullname = student.first + ' ' + student.last; } res.send({'loggedin' : true, 'netid' : netid, 'fullname': fullname}); }); } else { // CAS rejected the ticket res.send({'loggedin' : false}); } }); resp.on('error', function(e) { res.send({'loggedin' : false}); // just to be safe }); }).on('error', function(e) { console.log("Got error from CAS: " + e.message); res.send({'loggedin' : false}); // just to be safe }); } }); }); app.get('/auth/logout/:netid', function (req, res) { console.log('GET request for /auth/logout/' + req.params.netid); Ticket.find({netid: req.params.netid}).remove().exec(); res.end(); }); app.listen(3000); console.log('Server running at http://127.0.0.1:3000/');
backend/node/server.js
var http = require('http'); var https = require('https'); var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var crypto = require('crypto'); var async = require('async'); var fs = require('fs'); var app = express(); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data /* MongoDB Setup */ var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test-pp'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (callback) { console.log('mongoose: Connected to database \'test-pp\''); }); /* Collections */ var pollSchema = mongoose.Schema({ question: String, choices: [String], responses: [Number], author: String, time: Date, pid: String, upvotes: Number, downvotes: Number, score: Number }); var Poll = mongoose.model('Poll', pollSchema); var ticketSchema = mongoose.Schema({ netid: String, ticket: String }); var Ticket = mongoose.model('Ticket', ticketSchema); var userLogSchema = mongoose.Schema({ netid: String, time: Date }); var userLog = mongoose.model('userLog', userLogSchema); var voteSchema = mongoose.Schema({ netid: String, pid: String, upOrDown: Boolean //true is up }); var Vote = mongoose.model('Vote', voteSchema); var responseSchema = mongoose.Schema({ netid: String, pid: String, idx: Number //true is up }); var Response = mongoose.model('Response', responseSchema); var studentSchema = mongoose.Schema({ first: String, last: String, netid: String, 'class': String, home: String, major: String, dorm: String, rescol: String }); var Student = mongoose.model('Student', studentSchema); /* REST Handlers */ app.post('/polls/submit', function (req, res) { console.log('POST request for /polls/submit/'); //res.json(req.body); // parse request body, populate req.body object console.log(req.body); var newPoll = {}; newPoll.question = req.body.question; newPoll.choices = req.body.choices; newPoll.responses = []; for (var i in newPoll.choices) newPoll.responses.push(0); newPoll.author = req.body.author; newPoll.upvotes = 0; newPoll.downvotes = 0; newPoll.score = 0; var sha256 = crypto.createHash('sha256'); sha256.update(newPoll.question + newPoll.author); newPoll.pid = sha256.digest('hex'); newPoll.time = new Date(); var question = new Poll(newPoll); question.save(function (err) { if (err) return console.error(err); }); res.send({'pid' : newPoll.pid}); }); /* app.get('/polls/get/all', function (req, res) { console.log('GET request for /polls/get/all'); Poll.find({}, 'question choices time pid score', function (err, polls) { res.send(polls); }); }); */ app.get('/polls/get/:sortType/:netid/:num/:onlyUser', function(req, res) { console.log('GET request for /polls/' + req.params.sortType + '/' + req.params.netid + '/' + req.params.num); var user = req.params.netid; var current = req.params.num; var onlyUser = req.params.onlyUser; var sortBy; var fields; if (req.params.sortType == 'popular') sortBy = {'score': -1}; else if (req.params.sortType == 'newest') sortBy = {time: -1}; if (req.params.onlyUser == 'true') fields = {'author': user}; else if (req.params.onlyUser == 'false') fields = {}; Poll.find(fields).sort(sortBy).skip(current).limit(10).exec(function (err, polls) { var ret = []; async.eachSeries(polls, function(p, callback) { //console.log("date at start of loop: " + p.time); var pid = p.pid; var userVote; var userResponse; Vote.findOne({'pid' : pid, 'netid' : user}, function (err, vote) { //console.log(vote); if (vote != null) { //console.log('test'); userVote = vote.upOrDown; } else { userVote = null; } Response.findOne({pid: pid, netid: user}, function (err, response) { if (err) console.log('Error.'); if (response == null) userResponse = -1; else userResponse = response.idx; var newPollData = { pollData: p, userVote: userVote, userResponse: userResponse, isAuthor: p.author == user }; //console.log("time added into ret: " + newPollData.pollData.time); ret.push(newPollData); //console.log(ret.length); callback(); }) }); }, function(err) { if (err) console.log('Error.'); else { //console.log(polls.length + " " + ret.length); if (ret.length === 0) { res.send({err: true}); } else res.send(ret); } }); }); }); app.get('/polls/get/:pid/:netid', function(req, res) { console.log('GET request for /polls/get/' + req.params.pid + '/' + req.params.netid); Poll.findOne({'pid' : req.params.pid}, 'question choices responses time pid score author', function (err, poll) { if (err) console.log('Error.'); if (poll == null) res.send({'err': true, 'question': 'This poll does not exist.'}); else { var ret = {}; ret.question = poll.question; ret.choices = poll.choices; ret.responses = poll.responses; ret.time = poll.time; ret.pid = poll.pid; ret.score = poll.score; ret.isAuthor = poll.author === req.params.netid; Vote.findOne({'pid' : req.params.pid, 'netid' : req.params.netid}, function (err, vote) { //console.log(vote); if (vote != null) { console.log('test'); ret.userVote = vote.upOrDown; } else { ret.userVote = null; } Response.findOne({pid: req.params.pid, netid: req.params.netid}, function (err, response) { if (err) console.log('Error.'); if (response == null) ret.userResponse = -1; else ret.userResponse = response.idx; console.log(ret); res.send(ret); }) }); } }); }); // This + the get function above. Authentication? app.get('/polls/get/:netid', function(req, res) { var user = req.params.netid; console.log('GET request for /polls/get/' + user); Poll.find({"author": user}, 'question choices time pid score', function (err, polls) { res.send(polls); }); }); app.delete('/polls/delete/:pid/:netid/:ticket', function(req, res) { console.log('DELETE request for poll: ' + req.params.pid + ' by user: ' + req.params.netid); var pid = req.params.pid; var netid = req.params.netid; var ticket = req.params.ticket; Poll.findOne({pid: pid}, 'author', function (err, poll) { if (err) { console.log('Database error.'); res.send({err: true, msg: 'Database error.'}); return; } else if (poll == null) { console.log('Poll not found.'); res.send({err: true, msg: 'No poll with that ID found.'}); return; } else if (poll.author !== netid && netid !== 'roshea' && netid !== 'marchant' && netid != 'hzlu') { console.log('Non-author, non-admin tried to delete poll. Cancelling.'); res.send({err: true, msg: 'You are not the author of the given poll, so you can\'t delete it.'}); return; } else { Poll.findOneAndRemove({pid: pid}, function (err, poll) { Response.remove({pid: pid}, function (err) { Vote.remove({pid: pid}, function (err) { res.send({err: false}); }); }); }); } }); }); /* app.get('/polls/delete/all', function (req, res) { console.log('GET request for /polls/delete/all'); Poll.find({}).remove().exec(); Vote.find({}).remove().exec(); res.end(); }); */ // Plus send pid. app.post('/polls/vote', function (req, res) { console.log('POST request for /polls/vote'); //res.json(req.body); // parse request body, populate req.body object console.log(req.body); upOrDown = req.body.upOrDown; // up is true pollID = req.body.pollID; netid = req.body.netid; var reversed = false; var negated = false; if (netid !== null) { Vote.findOne({'pid' : pollID, 'netid' : netid}, 'upOrDown', function (err, oldVote) { if (err) console.log('Error with vote db.'); if (oldVote) { var oldUpOrDown = oldVote.upOrDown; console.log("new " + upOrDown); console.log("old " + oldUpOrDown); if (upOrDown == oldUpOrDown) { console.log("removing " + pollID + " " + netid); var conditions = {pid: pollID, netid: netid}; Vote.findOneAndRemove(conditions, function (err, results) { console.log("remove results: " + results); //** These two not guaranteed to execute in order }); //if already voted button pressed again negated = true; } else { var conditions = {pid: pollID, netid: netid}; var update = {upOrDown: upOrDown}; Vote.findOneAndUpdate(conditions, update, function (err, results) { console.log("updated results: " + results); //** Need to be made sync? }); //if other button pressed reversed = true; } } else { var newVoteFields = {}; newVoteFields.netid = netid; newVoteFields.upOrDown = upOrDown; newVoteFields.pid = pollID; var newVote = new Vote(newVoteFields); newVote.save(function (err) { if (err) return console.error(err); //if no button pressed yet }); } var conditions = {pid: pollID}; var update; console.log("negated " + negated); // This clusterfuck if (upOrDown) { if (reversed) { update = {$inc: {upvotes:1, downvotes: -1, score:2}}; } else if (negated) { update = {$inc: {upvotes:-1, score:-1}}; } else { update = {$inc: {upvotes:1, score:1}}; } } else { if (reversed) { update = {$inc: {downvotes:1, upvotes: -1, score:-2}}; } else if (negated) { update = {$inc: {downvotes:-1, score:1}}; } else { update = {$inc: {downvotes:1, score:-1}}; } } var options = {new: true}; Poll.findOneAndUpdate(conditions, update, options, function (err, updatedPoll) { console.log('New score: ' + updatedPoll); if (err) console.log('Error.'); if (updatedPoll == null) res.send({'err': true, 'question': 'This poll does not exist.'}); else { var ret = {}; ret.question = updatedPoll.question; ret.score = updatedPoll.score; ret.choices = updatedPoll.choices; ret.responses = updatedPoll.responses; ret.pid = updatedPoll.pid; if (negated) ret.userVote = null; else { ret.userVote = upOrDown; } res.send(ret); } }); }); } else { res.send({'err': true, 'netid': 'You are not logged in.'}); } }); /* Logs a user response to a poll. Returns the updated responses array for the poll. */ app.post('/polls/respond', function (req, res) { //res.json(req.body); // parse request body, populate req.body object console.log('POST request for /polls/respond'); console.log('Request contents: ' + req.body); var netid = req.body.netid; var pid = req.body.pid; var idx = req.body.idx; if (netid !== null) { Response.findOne({'netid': netid, 'pid': pid}, function (err, response) { if (err) console.log('Error.'); else if (response == null) { // Create new response object, update poll with new score for the right choice console.log('User ' + netid + ' has not responded to poll ' + pid + ' before. Creating new response.'); var newResp = {}; newResp.netid = netid; newResp.pid = pid; newResp.idx = idx; var entry = new Response(newResp); entry.save(function (err) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + idx] = 1; Poll.findOneAndUpdate({pid: pid}, update, function (err, poll) { if (err) { console.error(err); res.send({err: true}); } Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: idx}); } }); }); } }); } else { if (response.idx === idx) { // Revoke response console.log('User ' + netid + ' unselected their response to ' + pid + '. Revoking response.'); Response.findOneAndRemove({'netid': netid, 'pid': pid}, function (err, response) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + idx] = -1; Poll.findOneAndUpdate({pid: pid}, update, function (err, poll) { if (err) { console.error(err); res.send({err: true}); } else { Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: -1}); } }); } }); } }); } else { // Update response console.log('User ' + netid + ' has changed their response to ' + pid + '. Updating response.'); var update = {$set: {idx: idx}}; Response.findOneAndUpdate({pid: pid, netid: netid}, update, function (err, newResponse) { if (err) { console.error(err); res.send({err: true}); } else { var update = {$inc: {}}; update.$inc['responses.' + response.idx] = -1; update.$inc['responses.' + idx] = 1; Poll.findOneAndUpdate({pid: pid}, update, function (err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else { Poll.findOne({pid: pid}, function(err, newPoll) { if (err) { console.error(err); res.send({err: true}); } else if (newPoll == null) { res.send({err: true}); } else { res.send({responses: newPoll.responses, userResponse: idx}); } }); } }); } }); } } }); } }); // Indicates whether the provided CAS ticket (for just-after-login) or ticket/netid pair (for return // visits) are valid, and thus the user is logged in. Returns {loggedin : true/false}. app.post('/auth/loggedin', function (req, res) { console.log('POST request for /auth/loggedin'); // Check for the ticket in the db of currently-logged-in tickets/users var foundInDB = false; var sentTicket = {ticket: req.body.ticket, netid: req.body.netid}; Ticket.findOne({ticket: sentTicket.ticket}, function (err, ticket) { if (ticket != null) { // The user is already logged in console.log("Found user " + ticket.netid + " in database. Authenticated."); foundInDB = true; // Query for user's Full Name var fullname = ""; //Logging visitors var newLogDate = new Date(); var newUserLog = ticket.netid + " " + newLogDate + '\n'; fs.appendFile('userLog.txt', newUserLog, function (err) { if (err) console.log('Logging error'); }); Student.findOne({'netid': ticket.netid}, function (err, student) { if (err) console.log('Student db error'); if (student !== null) { fullname = student.first + ' ' + student.last; } res.send({'loggedin' : true, 'netid' : ticket.netid, 'fullname': fullname}); }); } else { // User not found in db; check with CAS's validation server console.log("Could not find user " + sentTicket.netid + " in database."); var casValidateUrl = 'https://fed.princeton.edu/cas/validate?ticket=' + req.body.ticket + '&service=' + req.body.returnUrl; console.log('Querying ' + casValidateUrl); var response = ""; https.get(casValidateUrl, function(resp) { resp.on('data', function(d) { // Piece chunks of response together response = response + d; }); resp.on('end', function(d) { // Response is ready, continue console.log('Response from CAS: ' + response); if (response.charAt(0) == 'y') { // CAS approved the ticket var netid = response.substring(response.indexOf('\n') + 1, response.length - 1); //Logging visitors var newLogDate = new Date(); var newUserLog = netid + " " + newLogDate + '\n'; fs.appendFile('userLog.txt', newUserLog, function (err) { if (err) console.log('Logging error'); }); var newTicket = {ticket: req.body.ticket, netid: netid}; console.log(newTicket); var saveTicket = new Ticket(newTicket); saveTicket.save(function (err) { if (err) console.log("Database ticket save error."); }); // Query for user's Full Name var fullname = ""; Student.findOne({'netid': netid}, function (err, student) { if (err) console.log('Student db error'); if (student !== null) { fullname = student.first + ' ' + student.last; } res.send({'loggedin' : true, 'netid' : netid, 'fullname': fullname}); }); } else { // CAS rejected the ticket res.send({'loggedin' : false}); } }); resp.on('error', function(e) { res.send({'loggedin' : false}); // just to be safe }); }).on('error', function(e) { console.log("Got error from CAS: " + e.message); res.send({'loggedin' : false}); // just to be safe }); } }); }); app.get('/auth/logout/:netid', function (req, res) { console.log('GET request for /auth/logout/' + req.params.netid); Ticket.find({netid: req.params.netid}).remove().exec(); res.end(); }); app.listen(3000); console.log('Server running at http://127.0.0.1:3000/');
Added unique count of visitors
backend/node/server.js
Added unique count of visitors
<ide><path>ackend/node/server.js <ide> <ide> //Logging visitors <ide> var newLogDate = new Date(); <del> var newUserLog = ticket.netid + " " + newLogDate + '\n'; <del> fs.appendFile('userLog.txt', newUserLog, function (err) <add> var log = ticket.netid + " " + newLogDate + '\n'; <add> var newUserLog = {netid: ticket.netid, time: newLogDate}; <add> var saveLog = new userLog(newUserLog); <add> userLog.findOne({netid: ticket.netid}, function(err, result) { <add> if (result == null) { <add> saveLog.save(function (err) { <add> console.log("saving unique user"); <add> if (err) <add> console.log("Database log save error."); <add> }); <add> } <add> }); <add> fs.appendFile('userLog.txt', log, function (err) <ide> { <ide> if (err) console.log('Logging error'); <ide> }); <ide> <ide> //Logging visitors <ide> var newLogDate = new Date(); <del> var newUserLog = netid + " " + newLogDate + '\n'; <del> fs.appendFile('userLog.txt', newUserLog, function (err) <add> var log = netid + " " + newLogDate + '\n'; <add> var newUserLog = {netid: netid, time: newLogDate}; <add> var saveLog = new userLog(newUserLog); <add> userLog.findOne({netid: netid}, function(err, result) { <add> if (result == null) { <add> saveLog.save(function (err) { <add> if (err) <add> console.log("Database log save error."); <add> }); <add> } <add> }); <add> fs.appendFile('userLog.txt', log, function (err) <ide> { <ide> if (err) console.log('Logging error'); <ide> }); <ide> <add> //Save ticket <ide> var newTicket = {ticket: req.body.ticket, netid: netid}; <ide> console.log(newTicket); <ide> var saveTicket = new Ticket(newTicket); <ide> if (err) <ide> console.log("Database ticket save error."); <ide> }); <del> <ide> // Query for user's Full Name <ide> var fullname = ""; <ide> Student.findOne({'netid': netid}, function (err, student) {
Java
apache-2.0
3d8fb564c2315c4a87c36d31a41401b606186982
0
adaptris/interlok
package com.adaptris.core.services.conditional; import com.adaptris.annotation.AdapterComponent; import com.adaptris.annotation.AdvancedConfig; import com.adaptris.annotation.ComponentProfile; import com.adaptris.annotation.DisplayOrder; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.CoreException; import com.adaptris.core.DefaultMessageFactory; import com.adaptris.core.MultiPayloadAdaptrisMessage; import com.adaptris.core.ServiceException; import com.adaptris.core.ServiceImp; import com.adaptris.core.util.Args; import com.adaptris.core.util.LifecycleHelper; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * A for-each implementation that iterates over the payloads in a * multi-payload message {@link MultiPayloadAdaptrisMessage}. For each * payload then execute the given service (list). The default is to use * a single thread to iterate over the payloads, but a thread pool can * be used to parallelize the loop. */ @XStreamAlias("for-each") @AdapterComponent @ComponentProfile( summary = "Runs the configured service/list for each multi-payload message payload.", tag = "for,each,for each,for-each,then,multi-payload") @DisplayOrder(order = {"then", "threadCount"}) public class ForEach extends ServiceImp { private static final transient Logger log = LoggerFactory.getLogger(ForEach.class.getName()); private static final int DEFAULT_THREAD_COUNT = 1; // default is single threaded @NotNull @Valid private ThenService then; @NotNull @Valid @AdvancedConfig private Integer threadCount = DEFAULT_THREAD_COUNT; /** * Get the for-each-then service. * * @return The service. */ public ThenService getThen() { return then; } /** * Set the for-each-then service. * * @param thenService The service. */ public void setThen(ThenService thenService) { this.then = thenService; } /** * Get the number of threads to use. * * @return The number of threads. */ public Integer getThreadCount() { return threadCount; } /** * Set the number of threads to use. * * If set to 0 then as many threads as there are payloads will be * used. * * @param threadCount The number of threads. */ public void setThreadCount(Integer threadCount) { Args.notNull(threadCount, "threadCount"); if (threadCount < 0) { log.warn("{} is a stupid thread count; will use payload count instead!", threadCount); threadCount = 0; } this.threadCount = threadCount; } /** * {@inheritDoc}. */ @Override public void doService(AdaptrisMessage msg) throws ServiceException { ThreadPoolExecutor executor = null; try { log.info("Starting for-each"); if (!(msg instanceof MultiPayloadAdaptrisMessage)) { log.warn("Message [{}] is not a multi-payload message!", msg.getUniqueId()); iterate(msg); } else { MultiPayloadAdaptrisMessage message = (MultiPayloadAdaptrisMessage)msg; int threads = threadCount; if (threads == 0) { // use as many threads as necessary threads = message.getPayloadCount(); } log.trace("Using {} thread{}", threads, threads > 1 ? "s" : ""); executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(threads); for (String id : message.getPayloadIDs()) { try { message.switchPayload(id); AdaptrisMessage each = DefaultMessageFactory.getDefaultInstance().newMessage(message, null); each.setPayload(message.getPayload()); executor.execute(() -> iterate(each)); } catch (CloneNotSupportedException e) { log.error("Could not clone message [{}]", id, e); } } } } finally { if (executor != null) { executor.shutdown(); try { while (!executor.awaitTermination(1, TimeUnit.MILLISECONDS)) { /* wait for all threads to complete */ } } catch (InterruptedException e) { log.warn("Interrupted while waiting for tasks to finish!", e); } } log.info("Finished for-each"); } } /** * Perform a single iteration of the then service on the given message. * * @param message The message to iterate over. */ private void iterate(AdaptrisMessage message) { String id = message.getUniqueId(); try { log.debug("Iterating over message [{}}]", id); then.getService().doService(message); } catch (Exception e) { log.error("Message [{}}] failed!", id, e); } finally { log.debug("Done with message [{}]", id); } } /** * {@inheritDoc} */ @Override protected void initService() throws CoreException { LifecycleHelper.init(then); } /** * {@inheritDoc} */ @Override protected void closeService() { LifecycleHelper.close(then); } /** * {@inheritDoc} */ @Override public void prepare() throws CoreException { LifecycleHelper.prepare(then); } /** * {@inheritDoc} */ @Override public void start() throws CoreException { LifecycleHelper.start(then); } /** * {@inheritDoc} */ @Override public void stop() { LifecycleHelper.stop(then); } }
interlok-core/src/main/java/com/adaptris/core/services/conditional/ForEach.java
package com.adaptris.core.services.conditional; import com.adaptris.annotation.AdapterComponent; import com.adaptris.annotation.AdvancedConfig; import com.adaptris.annotation.ComponentProfile; import com.adaptris.annotation.DisplayOrder; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.CoreException; import com.adaptris.core.DefaultMessageFactory; import com.adaptris.core.MultiPayloadAdaptrisMessage; import com.adaptris.core.ServiceException; import com.adaptris.core.ServiceImp; import com.adaptris.core.util.Args; import com.adaptris.core.util.LifecycleHelper; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * A for-each implementation that iterates over the payloads in a * multi-payload message {@link MultiPayloadAdaptrisMessage}. For each * payload then execute the given service (list). The default is to use * a single thread to iterate over the payloads, but a thread pool can * be used to parallelize the loop. */ @XStreamAlias("for-each") @AdapterComponent @ComponentProfile( summary = "Runs the configured service/list for each multi-payload message payload.", tag = "for,each,for each,for-each,then,multi-payload") @DisplayOrder(order = {"then", "threadCount"}) public class ForEach extends ServiceImp { private static final transient Logger log = LoggerFactory.getLogger(ForEach.class.getName()); private static final int DEFAULT_THREAD_COUNT = 1; // default is single threaded @NotNull @Valid private ThenService then; @NotNull @Valid @AdvancedConfig private Integer threadCount = DEFAULT_THREAD_COUNT; /** * Get the for-each-then service. * * @return The service. */ public ThenService getThen() { return then; } /** * Set the for-each-then service. * * @param thenService The service. */ public void setThen(ThenService thenService) { this.then = thenService; } /** * Get the number of threads to use. * * @return The number of threads. */ public Integer getThreadCount() { return threadCount; } /** * Set the number of threads to use. * * If set to 0 then as many threads as there are payloads will be * used. * * @param threadCount The number of threads. */ public void setThreadCount(Integer threadCount) { Args.notNull(threadCount, "threadCount"); if (threadCount < 0) { log.warn("{} is a stupid thread count; will use payload count instead!", threadCount); threadCount = 0; } this.threadCount = threadCount; } /** * {@inheritDoc}. */ @Override public void doService(AdaptrisMessage msg) throws ServiceException { ThreadPoolExecutor executor = null; try { log.info("Starting for-each"); if (!(msg instanceof MultiPayloadAdaptrisMessage)) { log.warn("Message [{}] is not a multi-payload message!", msg.getUniqueId()); iterate(msg); } else { MultiPayloadAdaptrisMessage message = (MultiPayloadAdaptrisMessage)msg; int threads = threadCount; if (threads == 0) { // use as many threads as necessary threads = message.getPayloadCount(); } log.trace("Using {} thread{}", threads, threads > 1 ? "s" : ""); executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(threads); for (String id : message.getPayloadIDs()) { try { message.switchPayload(id); AdaptrisMessage each = DefaultMessageFactory.getDefaultInstance().newMessage(message, null); executor.execute(() -> iterate(each)); } catch (CloneNotSupportedException e) { log.error("Could not clone message [{}]", id, e); } } } } finally { if (executor != null) { executor.shutdown(); try { while (!executor.awaitTermination(1, TimeUnit.MILLISECONDS)) { /* wait for all threads to complete */ } } catch (InterruptedException e) { log.warn("Interrupted while waiting for tasks to finish!", e); } } log.info("Finished for-each"); } } /** * Perform a single iteration of the then service on the given message. * * @param message The message to iterate over. */ private void iterate(AdaptrisMessage message) { String id = message.getUniqueId(); try { log.debug("Iterating over message [{}}]", id); then.getService().doService(message); } catch (Exception e) { log.error("Message [{}}] failed!", id, e); } finally { log.debug("Done with message [{}]", id); } } /** * {@inheritDoc} */ @Override protected void initService() throws CoreException { LifecycleHelper.init(then); } /** * {@inheritDoc} */ @Override protected void closeService() { LifecycleHelper.close(then); } /** * {@inheritDoc} */ @Override public void prepare() throws CoreException { LifecycleHelper.prepare(then); } /** * {@inheritDoc} */ @Override public void start() throws CoreException { LifecycleHelper.start(then); } /** * {@inheritDoc} */ @Override public void stop() { LifecycleHelper.stop(then); } }
INTERLOK-3087 Actually copy the payload to new messages
interlok-core/src/main/java/com/adaptris/core/services/conditional/ForEach.java
INTERLOK-3087 Actually copy the payload to new messages
<ide><path>nterlok-core/src/main/java/com/adaptris/core/services/conditional/ForEach.java <ide> { <ide> message.switchPayload(id); <ide> AdaptrisMessage each = DefaultMessageFactory.getDefaultInstance().newMessage(message, null); <add> each.setPayload(message.getPayload()); <ide> <ide> executor.execute(() -> iterate(each)); <ide> }
Java
agpl-3.0
df1b0ad46f127236950fad106b9230924767d476
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
a14cbee8-2e5f-11e5-9284-b827eb9e62be
hello.java
a14741ac-2e5f-11e5-9284-b827eb9e62be
a14cbee8-2e5f-11e5-9284-b827eb9e62be
hello.java
a14cbee8-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>a14741ac-2e5f-11e5-9284-b827eb9e62be <add>a14cbee8-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
d6487884131662bf510c920738036718bb4e66f7
0
julesbond007/Android-Jigsaw-Puzzle,julesbond007/Android-Jigsaw-Puzzle,RudraNilBasu/Android-Jigsaw-Puzzle
/* * Copyright (c) 2015. Jay Paulynice ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jigdraw.draw.activity; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Chronometer; import com.jigdraw.draw.R; import com.jigdraw.draw.model.LongParcelable; import com.jigdraw.draw.tasks.JigsawLoader; import com.jigdraw.draw.views.JigsawGridView; /** * Represents the jigsaw puzzle solving activity. A user creates a drawing * then selects a difficulty level (easy, medium, hard). On selecting ok, * this activity starts. * <p> * To initialize the puzzle grid, we create an asynchronous task to load the * images from the database, randomize the views and render them in the grid. * <p> * The images are stored in the local SQLite DB as Base64 encoded strings. * In the future, the ideal thing would be to offload the data through a * REST API to a central MySQL, PostGreSQL or NoSql database. * * @author Jay Paulynice */ public class JigsawActivity extends BaseJigsawActivity { /** The original image id to look up for jigsaw */ public static final String ORIGINAL_IMG_ID = "originalId"; /** Class name for logging */ private static final String TAG = "JigsawActivity"; /** Chronometer to display elapsed time */ private Chronometer chronometer; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "Starting jigsaw activity..."); super.onCreate(savedInstanceState); init(); } /** * Initialize all the views */ private void init() { setContentView(R.layout.activity_jigsaw); enableMenuBarUpButton(); initTimer(); initViews(); } /** * Initialize the chronometer */ private void initTimer() { chronometer = (Chronometer) findViewById(R.id.chronometer); chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); } /** * Initialize the jigsaw grid view */ private void initViews() { Log.d(TAG, "initializing jigsaw grid view"); final JigsawGridView gridView = (JigsawGridView) findViewById(R.id .jigsaw_grid); JigsawLoader task = new JigsawLoader(getApplicationContext(), gridView); LongParcelable longParcelable = getIntent().getExtras().getParcelable( ORIGINAL_IMG_ID); if (longParcelable == null) { throw new IllegalArgumentException("Parcelable can not be null."); } task.execute(longParcelable.getData()); gridView.setOnItemLongClickListener(onItemLongClickListener (gridView)); gridView.setOnDropListener(onDropListener(gridView)); gridView.setOnDragListener(onDragListener()); } /** * Listener to get hold of the click event to start the grid edit mode * * @param gridView the grid view * @return the item long click listener */ private JigsawGridView.OnItemLongClickListener onItemLongClickListener( final JigsawGridView gridView) { return new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { gridView.startEditMode(position); return true; } }; } /** * Listener to get hold of the drop event to stop the grid edit mode * * @param gridView the grid view * @return the drop listener */ private JigsawGridView.OnDropListener onDropListener( final JigsawGridView gridView) { return new JigsawGridView.OnDropListener() { @Override public void onActionDrop() { Log.d(TAG, "dropped element"); gridView.stopEditMode(); } }; } /** * Listener to get hold of the drag and position changed events * * @return the drag listener */ private JigsawGridView.OnDragListener onDragListener() { return new JigsawGridView.OnDragListener() { @Override public void onDragStarted(int position) { Log.d(TAG, "dragging starts...position: " + position); } @Override public void onDragPositionsChanged(int oldPosition, int newPosition) { Log.d(TAG, String.format("drag changed from %d to %d", oldPosition, newPosition)); } }; } }
app/src/main/java/com/jigdraw/draw/activity/JigsawActivity.java
/* * Copyright (c) 2015. Jay Paulynice ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jigdraw.draw.activity; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Chronometer; import com.jigdraw.draw.R; import com.jigdraw.draw.model.LongParcelable; import com.jigdraw.draw.tasks.JigsawLoader; import com.jigdraw.draw.views.JigsawGridView; /** * Represents the jigsaw puzzle solving activity. After a user creates a * drawing then selects the difficulty of the jigsaw and this activity starts. * * @author Jay Paulynice */ public class JigsawActivity extends BaseJigsawActivity { /** The original image id to look up for jigsaw */ public static final String ORIGINAL_IMG_ID = "originalId"; /** Class name for logging */ private static final String TAG = "JigsawActivity"; /** Chronometer to display elapsed time */ private Chronometer chronometer; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "Starting jigsaw activity..."); super.onCreate(savedInstanceState); init(); } /** * Initialize all the views */ private void init() { setContentView(R.layout.activity_jigsaw); enableMenuBarUpButton(); initTimer(); initViews(); } /** * Initialize the chronometer */ private void initTimer() { chronometer = (Chronometer) findViewById(R.id.chronometer); chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); } /** * Initialize the jigsaw grid view */ private void initViews() { Log.d(TAG, "initializing jigsaw grid view"); final JigsawGridView gridView = (JigsawGridView) findViewById(R.id .jigsaw_grid); JigsawLoader task = new JigsawLoader(getApplicationContext(), gridView); LongParcelable longParcelable = getIntent().getExtras().getParcelable( ORIGINAL_IMG_ID); if (longParcelable == null) { throw new IllegalArgumentException("Parcelable can not be null."); } task.execute(longParcelable.getData()); gridView.setOnItemLongClickListener(onItemLongClickListener (gridView)); gridView.setOnDropListener(onDropListener(gridView)); gridView.setOnDragListener(onDragListener()); } /** * Listener to get hold of the click event to start the grid edit mode * * @param gridView the grid view * @return the item long click listener */ private JigsawGridView.OnItemLongClickListener onItemLongClickListener( final JigsawGridView gridView) { return new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { gridView.startEditMode(position); return true; } }; } /** * Listener to get hold of the drop event to stop the grid edit mode * * @param gridView the grid view * @return the drop listener */ private JigsawGridView.OnDropListener onDropListener( final JigsawGridView gridView) { return new JigsawGridView.OnDropListener() { @Override public void onActionDrop() { Log.d(TAG, "dropped element"); gridView.stopEditMode(); } }; } /** * Listener to get hold of the drag and position changed events * * @return the drag listener */ private JigsawGridView.OnDragListener onDragListener() { return new JigsawGridView.OnDragListener() { @Override public void onDragStarted(int position) { Log.d(TAG, "dragging starts...position: " + position); } @Override public void onDragPositionsChanged(int oldPosition, int newPosition) { Log.d(TAG, String.format("drag changed from %d to %d", oldPosition, newPosition)); } }; } }
Update JigsawActivity.java
app/src/main/java/com/jigdraw/draw/activity/JigsawActivity.java
Update JigsawActivity.java
<ide><path>pp/src/main/java/com/jigdraw/draw/activity/JigsawActivity.java <ide> import com.jigdraw.draw.views.JigsawGridView; <ide> <ide> /** <del> * Represents the jigsaw puzzle solving activity. After a user creates a <del> * drawing then selects the difficulty of the jigsaw and this activity starts. <add> * Represents the jigsaw puzzle solving activity. A user creates a drawing <add> * then selects a difficulty level (easy, medium, hard). On selecting ok, <add> * this activity starts. <add> * <p> <add> * To initialize the puzzle grid, we create an asynchronous task to load the <add> * images from the database, randomize the views and render them in the grid. <add> * <p> <add> * The images are stored in the local SQLite DB as Base64 encoded strings. <add> * In the future, the ideal thing would be to offload the data through a <add> * REST API to a central MySQL, PostGreSQL or NoSql database. <ide> * <ide> * @author Jay Paulynice <ide> */
Java
apache-2.0
426944c524a7b9e0d4bd6c1c6b73fc893057c7de
0
ragerri/opennlp,apache/opennlp,ragerri/opennlp,apache/opennlp,ragerri/opennlp,apache/opennlp,jzonthemtn/opennlp,jzonthemtn/opennlp,jzonthemtn/opennlp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.parser; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import opennlp.tools.chunker.Chunker; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ngram.NGramModel; import opennlp.tools.parser.chunking.ParserEventStream; import opennlp.tools.postag.POSTagger; import opennlp.tools.util.Heap; import opennlp.tools.util.ListHeap; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.Sequence; import opennlp.tools.util.Span; import opennlp.tools.util.StringList; import opennlp.tools.util.TrainingParameters; /** * Abstract class which contains code to tag and chunk parses for bottom up parsing and * leaves implementation of advancing parses and completing parses to extend class. * <p> * <b>Note:</b> <br> The nodes within * the returned parses are shared with other parses and therefore their parent node references will not be consistent * with their child node reference. {@link #setParents setParents} can be used to make the parents consistent * with a particular parse, but subsequent calls to <code>setParents</code> can invalidate the results of earlier * calls.<br> */ public abstract class AbstractBottomUpParser implements Parser { /** * The maximum number of parses advanced from all preceding * parses at each derivation step. */ protected int M; /** * The maximum number of parses to advance from a single preceding parse. */ protected int K; /** * The minimum total probability mass of advanced outcomes. */ protected double Q; /** * The default beam size used if no beam size is given. */ public static final int defaultBeamSize = 20; /** * The default amount of probability mass required of advanced outcomes. */ public static final double defaultAdvancePercentage = 0.95; /** * Completed parses. */ protected Heap<Parse> completeParses; /** * Incomplete parses which will be advanced. */ protected Heap<Parse> odh; /** * Incomplete parses which have been advanced. */ protected Heap<Parse> ndh; /** * The head rules for the parser. */ protected HeadRules headRules; /** * The set strings which are considered punctuation for the parser. * Punctuation is not attached, but floats to the top of the parse as attachment * decisions are made about its non-punctuation sister nodes. */ protected Set<String> punctSet; /** * The label for the top node. */ public static final String TOP_NODE = "TOP"; /** * The label for the top if an incomplete node. */ public static final String INC_NODE = "INC"; /** * The label for a token node. */ public static final String TOK_NODE = "TK"; /** * The integer 0. */ public static final Integer ZERO = 0; /** * Prefix for outcomes starting a constituent. */ public static final String START = "S-"; /** * Prefix for outcomes continuing a constituent. */ public static final String CONT = "C-"; /** * Outcome for token which is not contained in a basal constituent. */ public static final String OTHER = "O"; /** * Outcome used when a constituent is complete. */ public static final String COMPLETE = "c"; /** * Outcome used when a constituent is incomplete. */ public static final String INCOMPLETE = "i"; /** * The pos-tagger that the parser uses. */ protected POSTagger tagger; /** * The chunker that the parser uses to chunk non-recursive structures. */ protected Chunker chunker; /** * Specifies whether failed parses should be reported to standard error. */ protected boolean reportFailedParse; /** * Specifies whether a derivation string should be created during parsing. * This is useful for debugging. */ protected boolean createDerivationString = false; /** * Turns debug print on or off. */ protected boolean debugOn = false; public AbstractBottomUpParser(POSTagger tagger, Chunker chunker, HeadRules headRules, int beamSize, double advancePercentage) { this.tagger = tagger; this.chunker = chunker; this.M = beamSize; this.K = beamSize; this.Q = advancePercentage; reportFailedParse = true; this.headRules = headRules; this.punctSet = headRules.getPunctuationTags(); odh = new ListHeap<Parse>(K); ndh = new ListHeap<Parse>(K); completeParses = new ListHeap<Parse>(K); } /** * Specifies whether the parser should report when it was unable to find a parse for * a particular sentence. * @param errorReporting If true then un-parsed sentences are reported, false otherwise. */ public void setErrorReporting(boolean errorReporting) { this.reportFailedParse = errorReporting; } /** * Assigns parent references for the specified parse so that they * are consistent with the children references. * @param p The parse whose parent references need to be assigned. */ public static void setParents(Parse p) { Parse[] children = p.getChildren(); for (int ci = 0; ci < children.length; ci++) { children[ci].setParent(p); setParents(children[ci]); } } /** * Removes the punctuation from the specified set of chunks, adds it to the parses * adjacent to the punctuation is specified, and returns a new array of parses with the punctuation * removed. * @param chunks A set of parses. * @param punctSet The set of punctuation which is to be removed. * @return An array of parses which is a subset of chunks with punctuation removed. */ public static Parse[] collapsePunctuation(Parse[] chunks, Set<String> punctSet) { List<Parse> collapsedParses = new ArrayList<Parse>(chunks.length); int lastNonPunct = -1; int nextNonPunct = -1; for (int ci=0,cn=chunks.length;ci<cn;ci++) { if (punctSet.contains(chunks[ci].getType())) { if (lastNonPunct >= 0) { chunks[lastNonPunct].addNextPunctuation(chunks[ci]); } for (nextNonPunct=ci+1;nextNonPunct<cn;nextNonPunct++) { if (!punctSet.contains(chunks[nextNonPunct].getType())) { break; } } if (nextNonPunct < cn) { chunks[nextNonPunct].addPreviousPunctuation(chunks[ci]); } } else { collapsedParses.add(chunks[ci]); lastNonPunct = ci; } } if (collapsedParses.size() == chunks.length) { return chunks; } //System.err.println("collapsedPunctuation: collapsedParses"+collapsedParses); return collapsedParses.toArray(new Parse[collapsedParses.size()]); } /** * Advances the specified parse and returns the an array advanced parses whose probability accounts for * more than the specified amount of probability mass. * @param p The parse to advance. * @param probMass The amount of probability mass that should be accounted for by the advanced parses. */ protected abstract Parse[] advanceParses(final Parse p, double probMass); /** * Adds the "TOP" node to the specified parse. * @param p The complete parse. */ protected abstract void advanceTop(Parse p); public Parse[] parse(Parse tokens, int numParses) { if (createDerivationString) tokens.setDerivation(new StringBuffer(100)); odh.clear(); ndh.clear(); completeParses.clear(); int derivationStage = 0; //derivation length int maxDerivationLength = 2 * tokens.getChildCount() + 3; odh.add(tokens); Parse guess = null; double minComplete = 2; double bestComplete = -100000; //approximating -infinity/0 in ln domain while (odh.size() > 0 && (completeParses.size() < M || (odh.first()).getProb() < minComplete) && derivationStage < maxDerivationLength) { ndh = new ListHeap<Parse>(K); int derivationRank = 0; for (Iterator<Parse> pi = odh.iterator(); pi.hasNext() && derivationRank < K; derivationRank++) { // forearch derivation Parse tp = pi.next(); //TODO: Need to look at this for K-best parsing cases /* if (tp.getProb() < bestComplete) { //this parse and the ones which follow will never win, stop advancing. break; } */ if (guess == null && derivationStage == 2) { guess = tp; } if (debugOn) { System.out.print(derivationStage + " " + derivationRank + " "+tp.getProb()); tp.show(); System.out.println(); } Parse[] nd; if (0 == derivationStage) { nd = advanceTags(tp); } else if (1 == derivationStage) { if (ndh.size() < K) { //System.err.println("advancing ts "+j+" "+ndh.size()+" < "+K); nd = advanceChunks(tp,bestComplete); } else { //System.err.println("advancing ts "+j+" prob="+((Parse) ndh.last()).getProb()); nd = advanceChunks(tp,(ndh.last()).getProb()); } } else { // i > 1 nd = advanceParses(tp, Q); } if (nd != null) { for (int k = 0, kl = nd.length; k < kl; k++) { if (nd[k].complete()) { advanceTop(nd[k]); if (nd[k].getProb() > bestComplete) { bestComplete = nd[k].getProb(); } if (nd[k].getProb() < minComplete) { minComplete = nd[k].getProb(); } completeParses.add(nd[k]); } else { ndh.add(nd[k]); } } } else { //if (reportFailedParse) { // System.err.println("Couldn't advance parse "+derivationStage+" stage "+derivationRank+"!\n"); //} advanceTop(tp); completeParses.add(tp); } } derivationStage++; odh = ndh; } if (completeParses.size() == 0) { // if (reportFailedParse) System.err.println("Couldn't find parse for: " + tokens); //Parse r = (Parse) odh.first(); //r.show(); //System.out.println(); return new Parse[] {guess}; } else if (numParses == 1){ return new Parse[] {completeParses.first()}; } else { List<Parse> topParses = new ArrayList<Parse>(numParses); while(!completeParses.isEmpty() && topParses.size() < numParses) { Parse tp = completeParses.extract(); topParses.add(tp); //parses.remove(tp); } return topParses.toArray(new Parse[topParses.size()]); } } public Parse parse(Parse tokens) { if (tokens.getChildCount() > 0) { Parse p = parse(tokens,1)[0]; setParents(p); return p; } else { return tokens; } } /** * Returns the top chunk sequences for the specified parse. * @param p A pos-tag assigned parse. * @param minChunkScore A minimum score below which chunks should not be advanced. * @return The top chunk assignments to the specified parse. */ protected Parse[] advanceChunks(final Parse p, double minChunkScore) { // chunk Parse[] children = p.getChildren(); String words[] = new String[children.length]; String ptags[] = new String[words.length]; double probs[] = new double[words.length]; Parse sp = null; for (int i = 0, il = children.length; i < il; i++) { sp = children[i]; words[i] = sp.getHead().getCoveredText(); ptags[i] = sp.getType(); } //System.err.println("adjusted mcs = "+(minChunkScore-p.getProb())); Sequence[] cs = chunker.topKSequences(words, ptags,minChunkScore-p.getProb()); Parse[] newParses = new Parse[cs.length]; for (int si = 0, sl = cs.length; si < sl; si++) { newParses[si] = (Parse) p.clone(); //copies top level if (createDerivationString) newParses[si].getDerivation().append(si).append("."); String[] tags = cs[si].getOutcomes().toArray(new String[words.length]); cs[si].getProbs(probs); int start = -1; int end = 0; String type = null; //System.err.print("sequence "+si+" "); for (int j = 0; j <= tags.length; j++) { //if (j != tags.length) {System.err.println(words[j]+" "+ptags[j]+" "+tags[j]+" "+probs.get(j));} if (j != tags.length) { newParses[si].addProb(Math.log(probs[j])); } if (j != tags.length && tags[j].startsWith(CONT)) { // if continue just update end chunking tag don't use contTypeMap end = j; } else { //make previous constituent if it exists if (type != null) { //System.err.println("inserting tag "+tags[j]); Parse p1 = p.getChildren()[start]; Parse p2 = p.getChildren()[end]; //System.err.println("Putting "+type+" at "+start+","+end+" for "+j+" "+newParses[si].getProb()); Parse[] cons = new Parse[end - start + 1]; cons[0] = p1; //cons[0].label="Start-"+type; if (end - start != 0) { cons[end - start] = p2; //cons[end-start].label="Cont-"+type; for (int ci = 1; ci < end - start; ci++) { cons[ci] = p.getChildren()[ci + start]; //cons[ci].label="Cont-"+type; } } Parse chunk = new Parse(p1.getText(), new Span(p1.getSpan().getStart(), p2.getSpan().getEnd()), type, 1, headRules.getHead(cons, type)); chunk.isChunk(true); newParses[si].insert(chunk); } if (j != tags.length) { //update for new constituent if (tags[j].startsWith(START)) { // don't use startTypeMap these are chunk tags type = tags[j].substring(START.length()); start = j; end = j; } else { // other type = null; } } } } //newParses[si].show();System.out.println(); } return newParses; } /** * Advances the parse by assigning it POS tags and returns multiple tag sequences. * @param p The parse to be tagged. * @return Parses with different POS-tag sequence assignments. */ protected Parse[] advanceTags(final Parse p) { Parse[] children = p.getChildren(); String[] words = new String[children.length]; double[] probs = new double[words.length]; for (int i = 0,il = children.length; i < il; i++) { words[i] = children[i].getCoveredText(); } Sequence[] ts = tagger.topKSequences(words); // if (ts.length == 0) { // System.err.println("no tag sequence"); // } Parse[] newParses = new Parse[ts.length]; for (int i = 0; i < ts.length; i++) { String[] tags = ts[i].getOutcomes().toArray(new String[words.length]); ts[i].getProbs(probs); newParses[i] = (Parse) p.clone(); //copies top level if (createDerivationString) newParses[i].getDerivation().append(i).append("."); for (int j = 0; j < words.length; j++) { Parse word = children[j]; //System.err.println("inserting tag "+tags[j]); double prob = probs[j]; newParses[i].insert(new Parse(word.getText(), word.getSpan(), tags[j], prob,j)); newParses[i].addProb(Math.log(prob)); //newParses[i].show(); } } return newParses; } /** * Determines the mapping between the specified index into the specified parses without punctuation to * the corresponding index into the specified parses. * @param index An index into the parses without punctuation. * @param nonPunctParses The parses without punctuation. * @param parses The parses wit punctuation. * @return An index into the specified parses which corresponds to the same node the specified index * into the parses with punctuation. */ protected int mapParseIndex(int index, Parse[] nonPunctParses, Parse[] parses) { int parseIndex = index; while (parses[parseIndex] != nonPunctParses[index]) { parseIndex++; } return parseIndex; } private static boolean lastChild(Parse child, Parse parent, Set<String> punctSet) { if (parent == null) { return false; } Parse[] kids = collapsePunctuation(parent.getChildren(), punctSet); return (kids[kids.length - 1] == child); } /** * Creates a n-gram dictionary from the specified data stream using the specified head rule and specified cut-off. * * @param data The data stream of parses. * @param rules The head rules for the parses. * @param params can contain a cutoff, the minimum number of entries required for the * n-gram to be saved as part of the dictionary. * @return A dictionary object. */ public static Dictionary buildDictionary(ObjectStream<Parse> data, HeadRules rules, TrainingParameters params) throws IOException { int cutoff = 5; String cutoffString = params.getSettings("dict"). get(TrainingParameters.CUTOFF_PARAM); if (cutoffString != null) { // TODO: Maybe throw illegal argument exception if not parse able cutoff = Integer.parseInt(cutoffString); } NGramModel mdict = new NGramModel(); Parse p; while((p = data.read()) != null) { p.updateHeads(rules); Parse[] pwords = p.getTagNodes(); String[] words = new String[pwords.length]; //add all uni-grams for (int wi=0;wi<words.length;wi++) { words[wi] = pwords[wi].getCoveredText(); } mdict.add(new StringList(words), 1, 1); //add tri-grams and bi-grams for inital sequence Parse[] chunks = collapsePunctuation(ParserEventStream.getInitialChunks(p),rules.getPunctuationTags()); String[] cwords = new String[chunks.length]; for (int wi=0;wi<cwords.length;wi++) { cwords[wi] = chunks[wi].getHead().getCoveredText(); } mdict.add(new StringList(cwords), 2, 3); //emulate reductions to produce additional n-grams int ci = 0; while (ci < chunks.length) { //System.err.println("chunks["+ci+"]="+chunks[ci].getHead().getCoveredText()+" chunks.length="+chunks.length + " " + chunks[ci].getParent()); if (chunks[ci].getParent() == null) { chunks[ci].show(); } if (lastChild(chunks[ci], chunks[ci].getParent(),rules.getPunctuationTags())) { //perform reduce int reduceStart = ci; while (reduceStart >=0 && chunks[reduceStart].getParent() == chunks[ci].getParent()) { reduceStart--; } reduceStart++; chunks = ParserEventStream.reduceChunks(chunks,ci,chunks[ci].getParent()); ci = reduceStart; if (chunks.length != 0) { String[] window = new String[5]; int wi = 0; if (ci-2 >= 0) window[wi++] = chunks[ci-2].getHead().getCoveredText(); if (ci-1 >= 0) window[wi++] = chunks[ci-1].getHead().getCoveredText(); window[wi++] = chunks[ci].getHead().getCoveredText(); if (ci+1 < chunks.length) window[wi++] = chunks[ci+1].getHead().getCoveredText(); if (ci+2 < chunks.length) window[wi++] = chunks[ci+2].getHead().getCoveredText(); if (wi < 5) { String[] subWindow = new String[wi]; for (int swi=0;swi<wi;swi++) { subWindow[swi]=window[swi]; } window = subWindow; } if (window.length >=3) { mdict.add(new StringList(window), 2, 3); } else if (window.length == 2) { mdict.add(new StringList(window), 2, 2); } } ci=reduceStart-1; //ci will be incremented at end of loop } ci++; } } //System.err.println("gas,and="+mdict.getCount((new TokenList(new String[] {"gas","and"})))); mdict.cutoff(cutoff, Integer.MAX_VALUE); return mdict.toDictionary(true); } /** * Creates a n-gram dictionary from the specified data stream using the specified head rule and specified cut-off. * * @param data The data stream of parses. * @param rules The head rules for the parses. * @param cutoff The minimum number of entries required for the n-gram to be saved as part of the dictionary. * @return A dictionary object. */ public static Dictionary buildDictionary(ObjectStream<Parse> data, HeadRules rules, int cutoff) throws IOException { TrainingParameters params = new TrainingParameters(); params.put("dict", TrainingParameters.CUTOFF_PARAM, Integer.toString(cutoff)); return buildDictionary(data, rules, params); } }
opennlp-tools/src/main/java/opennlp/tools/parser/AbstractBottomUpParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.parser; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import opennlp.tools.chunker.Chunker; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ngram.NGramModel; import opennlp.tools.parser.chunking.ParserEventStream; import opennlp.tools.postag.POSTagger; import opennlp.tools.util.Heap; import opennlp.tools.util.ListHeap; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.Sequence; import opennlp.tools.util.Span; import opennlp.tools.util.StringList; import opennlp.tools.util.TrainingParameters; /** * Abstract class which contains code to tag and chunk parses for bottom up parsing and * leaves implementation of advancing parses and completing parses to extend class. * <p> * <b>Note:</b> <br> The nodes within * the returned parses are shared with other parses and therefore their parent node references will not be consistent * with their child node reference. {@link #setParents setParents} can be used to make the parents consistent * with a particular parse, but subsequent calls to <code>setParents</code> can invalidate the results of earlier * calls.<br> */ public abstract class AbstractBottomUpParser implements Parser { /** * The maximum number of parses advanced from all preceding * parses at each derivation step. */ protected int M; /** * The maximum number of parses to advance from a single preceding parse. */ protected int K; /** * The minimum total probability mass of advanced outcomes. */ protected double Q; /** * The default beam size used if no beam size is given. */ public static final int defaultBeamSize = 20; /** * The default amount of probability mass required of advanced outcomes. */ public static final double defaultAdvancePercentage = 0.95; /** * Completed parses. */ protected Heap<Parse> completeParses; /** * Incomplete parses which will be advanced. */ protected Heap<Parse> odh; /** * Incomplete parses which have been advanced. */ protected Heap<Parse> ndh; /** * The head rules for the parser. */ protected HeadRules headRules; /** * The set strings which are considered punctuation for the parser. * Punctuation is not attached, but floats to the top of the parse as attachment * decisions are made about its non-punctuation sister nodes. */ protected Set<String> punctSet; /** * The label for the top node. */ public static final String TOP_NODE = "TOP"; /** * The label for the top if an incomplete node. */ public static final String INC_NODE = "INC"; /** * The label for a token node. */ public static final String TOK_NODE = "TK"; /** * The integer 0. */ public static final Integer ZERO = 0; /** * Prefix for outcomes starting a constituent. */ public static final String START = "S-"; /** * Prefix for outcomes continuing a constituent. */ public static final String CONT = "C-"; /** * Outcome for token which is not contained in a basal constituent. */ public static final String OTHER = "O"; /** * Outcome used when a constituent is complete. */ public static final String COMPLETE = "c"; /** * Outcome used when a constituent is incomplete. */ public static final String INCOMPLETE = "i"; /** * The pos-tagger that the parser uses. */ protected POSTagger tagger; /** * The chunker that the parser uses to chunk non-recursive structures. */ protected Chunker chunker; /** * Specifies whether failed parses should be reported to standard error. */ protected boolean reportFailedParse; /** * Specifies whether a derivation string should be created during parsing. * This is useful for debugging. */ protected boolean createDerivationString = false; /** * Turns debug print on or off. */ protected boolean debugOn = false; public AbstractBottomUpParser(POSTagger tagger, Chunker chunker, HeadRules headRules, int beamSize, double advancePercentage) { this.tagger = tagger; this.chunker = chunker; this.M = beamSize; this.K = beamSize; this.Q = advancePercentage; reportFailedParse = true; this.headRules = headRules; this.punctSet = headRules.getPunctuationTags(); odh = new ListHeap<Parse>(K); ndh = new ListHeap<Parse>(K); completeParses = new ListHeap<Parse>(K); } /** * Specifies whether the parser should report when it was unable to find a parse for * a particular sentence. * @param errorReporting If true then un-parsed sentences are reported, false otherwise. */ public void setErrorReporting(boolean errorReporting) { this.reportFailedParse = errorReporting; } /** * Assigns parent references for the specified parse so that they * are consistent with the children references. * @param p The parse whose parent references need to be assigned. */ public static void setParents(Parse p) { Parse[] children = p.getChildren(); for (int ci = 0; ci < children.length; ci++) { children[ci].setParent(p); setParents(children[ci]); } } /** * Removes the punctuation from the specified set of chunks, adds it to the parses * adjacent to the punctuation is specified, and returns a new array of parses with the punctuation * removed. * @param chunks A set of parses. * @param punctSet The set of punctuation which is to be removed. * @return An array of parses which is a subset of chunks with punctuation removed. */ public static Parse[] collapsePunctuation(Parse[] chunks, Set<String> punctSet) { List<Parse> collapsedParses = new ArrayList<Parse>(chunks.length); int lastNonPunct = -1; int nextNonPunct = -1; for (int ci=0,cn=chunks.length;ci<cn;ci++) { if (punctSet.contains(chunks[ci].getType())) { if (lastNonPunct >= 0) { chunks[lastNonPunct].addNextPunctuation(chunks[ci]); } for (nextNonPunct=ci+1;nextNonPunct<cn;nextNonPunct++) { if (!punctSet.contains(chunks[nextNonPunct].getType())) { break; } } if (nextNonPunct < cn) { chunks[nextNonPunct].addPreviousPunctuation(chunks[ci]); } } else { collapsedParses.add(chunks[ci]); lastNonPunct = ci; } } if (collapsedParses.size() == chunks.length) { return chunks; } //System.err.println("collapsedPunctuation: collapsedParses"+collapsedParses); return collapsedParses.toArray(new Parse[collapsedParses.size()]); } /** * Advances the specified parse and returns the an array advanced parses whose probability accounts for * more than the specified amount of probability mass. * @param p The parse to advance. * @param probMass The amount of probability mass that should be accounted for by the advanced parses. */ protected abstract Parse[] advanceParses(final Parse p, double probMass); /** * Adds the "TOP" node to the specified parse. * @param p The complete parse. */ protected abstract void advanceTop(Parse p); public Parse[] parse(Parse tokens, int numParses) { if (createDerivationString) tokens.setDerivation(new StringBuffer(100)); odh.clear(); ndh.clear(); completeParses.clear(); int derivationStage = 0; //derivation length int maxDerivationLength = 2 * tokens.getChildCount() + 3; odh.add(tokens); Parse guess = null; double minComplete = 2; double bestComplete = -100000; //approximating -infinity/0 in ln domain while (odh.size() > 0 && (completeParses.size() < M || (odh.first()).getProb() < minComplete) && derivationStage < maxDerivationLength) { ndh = new ListHeap<Parse>(K); int derivationRank = 0; for (Iterator<Parse> pi = odh.iterator(); pi.hasNext() && derivationRank < K; derivationRank++) { // forearch derivation Parse tp = pi.next(); //TODO: Need to look at this for K-best parsing cases /* if (tp.getProb() < bestComplete) { //this parse and the ones which follow will never win, stop advancing. break; } */ if (guess == null && derivationStage == 2) { guess = tp; } if (debugOn) { System.out.print(derivationStage + " " + derivationRank + " "+tp.getProb()); tp.show(); System.out.println(); } Parse[] nd; if (0 == derivationStage) { nd = advanceTags(tp); } else if (1 == derivationStage) { if (ndh.size() < K) { //System.err.println("advancing ts "+j+" "+ndh.size()+" < "+K); nd = advanceChunks(tp,bestComplete); } else { //System.err.println("advancing ts "+j+" prob="+((Parse) ndh.last()).getProb()); nd = advanceChunks(tp,(ndh.last()).getProb()); } } else { // i > 1 nd = advanceParses(tp, Q); } if (nd != null) { for (int k = 0, kl = nd.length; k < kl; k++) { if (nd[k].complete()) { advanceTop(nd[k]); if (nd[k].getProb() > bestComplete) { bestComplete = nd[k].getProb(); } if (nd[k].getProb() < minComplete) { minComplete = nd[k].getProb(); } completeParses.add(nd[k]); } else { ndh.add(nd[k]); } } } else { if (reportFailedParse) { System.err.println("Couldn't advance parse "+derivationStage+" stage "+derivationRank+"!\n"); } advanceTop(tp); completeParses.add(tp); } } derivationStage++; odh = ndh; } if (completeParses.size() == 0) { if (reportFailedParse) System.err.println("Couldn't find parse for: " + tokens); //Parse r = (Parse) odh.first(); //r.show(); //System.out.println(); return new Parse[] {guess}; } else if (numParses == 1){ return new Parse[] {completeParses.first()}; } else { List<Parse> topParses = new ArrayList<Parse>(numParses); while(!completeParses.isEmpty() && topParses.size() < numParses) { Parse tp = completeParses.extract(); topParses.add(tp); //parses.remove(tp); } return topParses.toArray(new Parse[topParses.size()]); } } public Parse parse(Parse tokens) { if (tokens.getChildCount() > 0) { Parse p = parse(tokens,1)[0]; setParents(p); return p; } else { return tokens; } } /** * Returns the top chunk sequences for the specified parse. * @param p A pos-tag assigned parse. * @param minChunkScore A minimum score below which chunks should not be advanced. * @return The top chunk assignments to the specified parse. */ protected Parse[] advanceChunks(final Parse p, double minChunkScore) { // chunk Parse[] children = p.getChildren(); String words[] = new String[children.length]; String ptags[] = new String[words.length]; double probs[] = new double[words.length]; Parse sp = null; for (int i = 0, il = children.length; i < il; i++) { sp = children[i]; words[i] = sp.getHead().getCoveredText(); ptags[i] = sp.getType(); } //System.err.println("adjusted mcs = "+(minChunkScore-p.getProb())); Sequence[] cs = chunker.topKSequences(words, ptags,minChunkScore-p.getProb()); Parse[] newParses = new Parse[cs.length]; for (int si = 0, sl = cs.length; si < sl; si++) { newParses[si] = (Parse) p.clone(); //copies top level if (createDerivationString) newParses[si].getDerivation().append(si).append("."); String[] tags = cs[si].getOutcomes().toArray(new String[words.length]); cs[si].getProbs(probs); int start = -1; int end = 0; String type = null; //System.err.print("sequence "+si+" "); for (int j = 0; j <= tags.length; j++) { //if (j != tags.length) {System.err.println(words[j]+" "+ptags[j]+" "+tags[j]+" "+probs.get(j));} if (j != tags.length) { newParses[si].addProb(Math.log(probs[j])); } if (j != tags.length && tags[j].startsWith(CONT)) { // if continue just update end chunking tag don't use contTypeMap end = j; } else { //make previous constituent if it exists if (type != null) { //System.err.println("inserting tag "+tags[j]); Parse p1 = p.getChildren()[start]; Parse p2 = p.getChildren()[end]; //System.err.println("Putting "+type+" at "+start+","+end+" for "+j+" "+newParses[si].getProb()); Parse[] cons = new Parse[end - start + 1]; cons[0] = p1; //cons[0].label="Start-"+type; if (end - start != 0) { cons[end - start] = p2; //cons[end-start].label="Cont-"+type; for (int ci = 1; ci < end - start; ci++) { cons[ci] = p.getChildren()[ci + start]; //cons[ci].label="Cont-"+type; } } Parse chunk = new Parse(p1.getText(), new Span(p1.getSpan().getStart(), p2.getSpan().getEnd()), type, 1, headRules.getHead(cons, type)); chunk.isChunk(true); newParses[si].insert(chunk); } if (j != tags.length) { //update for new constituent if (tags[j].startsWith(START)) { // don't use startTypeMap these are chunk tags type = tags[j].substring(START.length()); start = j; end = j; } else { // other type = null; } } } } //newParses[si].show();System.out.println(); } return newParses; } /** * Advances the parse by assigning it POS tags and returns multiple tag sequences. * @param p The parse to be tagged. * @return Parses with different POS-tag sequence assignments. */ protected Parse[] advanceTags(final Parse p) { Parse[] children = p.getChildren(); String[] words = new String[children.length]; double[] probs = new double[words.length]; for (int i = 0,il = children.length; i < il; i++) { words[i] = children[i].getCoveredText(); } Sequence[] ts = tagger.topKSequences(words); // if (ts.length == 0) { // System.err.println("no tag sequence"); // } Parse[] newParses = new Parse[ts.length]; for (int i = 0; i < ts.length; i++) { String[] tags = ts[i].getOutcomes().toArray(new String[words.length]); ts[i].getProbs(probs); newParses[i] = (Parse) p.clone(); //copies top level if (createDerivationString) newParses[i].getDerivation().append(i).append("."); for (int j = 0; j < words.length; j++) { Parse word = children[j]; //System.err.println("inserting tag "+tags[j]); double prob = probs[j]; newParses[i].insert(new Parse(word.getText(), word.getSpan(), tags[j], prob,j)); newParses[i].addProb(Math.log(prob)); //newParses[i].show(); } } return newParses; } /** * Determines the mapping between the specified index into the specified parses without punctuation to * the corresponding index into the specified parses. * @param index An index into the parses without punctuation. * @param nonPunctParses The parses without punctuation. * @param parses The parses wit punctuation. * @return An index into the specified parses which corresponds to the same node the specified index * into the parses with punctuation. */ protected int mapParseIndex(int index, Parse[] nonPunctParses, Parse[] parses) { int parseIndex = index; while (parses[parseIndex] != nonPunctParses[index]) { parseIndex++; } return parseIndex; } private static boolean lastChild(Parse child, Parse parent, Set<String> punctSet) { if (parent == null) { return false; } Parse[] kids = collapsePunctuation(parent.getChildren(), punctSet); return (kids[kids.length - 1] == child); } /** * Creates a n-gram dictionary from the specified data stream using the specified head rule and specified cut-off. * * @param data The data stream of parses. * @param rules The head rules for the parses. * @param params can contain a cutoff, the minimum number of entries required for the * n-gram to be saved as part of the dictionary. * @return A dictionary object. */ public static Dictionary buildDictionary(ObjectStream<Parse> data, HeadRules rules, TrainingParameters params) throws IOException { int cutoff = 5; String cutoffString = params.getSettings("dict"). get(TrainingParameters.CUTOFF_PARAM); if (cutoffString != null) { // TODO: Maybe throw illegal argument exception if not parse able cutoff = Integer.parseInt(cutoffString); } NGramModel mdict = new NGramModel(); Parse p; while((p = data.read()) != null) { p.updateHeads(rules); Parse[] pwords = p.getTagNodes(); String[] words = new String[pwords.length]; //add all uni-grams for (int wi=0;wi<words.length;wi++) { words[wi] = pwords[wi].getCoveredText(); } mdict.add(new StringList(words), 1, 1); //add tri-grams and bi-grams for inital sequence Parse[] chunks = collapsePunctuation(ParserEventStream.getInitialChunks(p),rules.getPunctuationTags()); String[] cwords = new String[chunks.length]; for (int wi=0;wi<cwords.length;wi++) { cwords[wi] = chunks[wi].getHead().getCoveredText(); } mdict.add(new StringList(cwords), 2, 3); //emulate reductions to produce additional n-grams int ci = 0; while (ci < chunks.length) { //System.err.println("chunks["+ci+"]="+chunks[ci].getHead().getCoveredText()+" chunks.length="+chunks.length + " " + chunks[ci].getParent()); if (chunks[ci].getParent() == null) { chunks[ci].show(); } if (lastChild(chunks[ci], chunks[ci].getParent(),rules.getPunctuationTags())) { //perform reduce int reduceStart = ci; while (reduceStart >=0 && chunks[reduceStart].getParent() == chunks[ci].getParent()) { reduceStart--; } reduceStart++; chunks = ParserEventStream.reduceChunks(chunks,ci,chunks[ci].getParent()); ci = reduceStart; if (chunks.length != 0) { String[] window = new String[5]; int wi = 0; if (ci-2 >= 0) window[wi++] = chunks[ci-2].getHead().getCoveredText(); if (ci-1 >= 0) window[wi++] = chunks[ci-1].getHead().getCoveredText(); window[wi++] = chunks[ci].getHead().getCoveredText(); if (ci+1 < chunks.length) window[wi++] = chunks[ci+1].getHead().getCoveredText(); if (ci+2 < chunks.length) window[wi++] = chunks[ci+2].getHead().getCoveredText(); if (wi < 5) { String[] subWindow = new String[wi]; for (int swi=0;swi<wi;swi++) { subWindow[swi]=window[swi]; } window = subWindow; } if (window.length >=3) { mdict.add(new StringList(window), 2, 3); } else if (window.length == 2) { mdict.add(new StringList(window), 2, 2); } } ci=reduceStart-1; //ci will be incremented at end of loop } ci++; } } //System.err.println("gas,and="+mdict.getCount((new TokenList(new String[] {"gas","and"})))); mdict.cutoff(cutoff, Integer.MAX_VALUE); return mdict.toDictionary(true); } /** * Creates a n-gram dictionary from the specified data stream using the specified head rule and specified cut-off. * * @param data The data stream of parses. * @param rules The head rules for the parses. * @param cutoff The minimum number of entries required for the n-gram to be saved as part of the dictionary. * @return A dictionary object. */ public static Dictionary buildDictionary(ObjectStream<Parse> data, HeadRules rules, int cutoff) throws IOException { TrainingParameters params = new TrainingParameters(); params.put("dict", TrainingParameters.CUTOFF_PARAM, Integer.toString(cutoff)); return buildDictionary(data, rules, params); } }
Comment debug log if parse can't be found See issue OPENNLP-869
opennlp-tools/src/main/java/opennlp/tools/parser/AbstractBottomUpParser.java
Comment debug log if parse can't be found
<ide><path>pennlp-tools/src/main/java/opennlp/tools/parser/AbstractBottomUpParser.java <ide> } <ide> } <ide> else { <del> if (reportFailedParse) { <del> System.err.println("Couldn't advance parse "+derivationStage+" stage "+derivationRank+"!\n"); <del> } <add> //if (reportFailedParse) { <add> // System.err.println("Couldn't advance parse "+derivationStage+" stage "+derivationRank+"!\n"); <add> //} <ide> advanceTop(tp); <ide> completeParses.add(tp); <ide> } <ide> odh = ndh; <ide> } <ide> if (completeParses.size() == 0) { <del> if (reportFailedParse) System.err.println("Couldn't find parse for: " + tokens); <add> // if (reportFailedParse) System.err.println("Couldn't find parse for: " + tokens); <ide> //Parse r = (Parse) odh.first(); <ide> //r.show(); <ide> //System.out.println();
Java
mit
9e34eb21110b9538f5f0e8a23af8da399379052f
0
Innovimax-SARL/mix-them
package innovimax.mixthem.operation; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Map; /** * <p>Abstract class for all line operation.</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public abstract class AbstractLineOperation extends AbstractOperation implements ILineOperation { /** * Constructor * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public AbstractLineOperation(Map<RuleParam, ParamValue> params) { super(params); } }
src/main/java/innovimax/mixthem/operation/AbstractLineOperation.java
package innovimax.mixthem.operation; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Map; /** * <p>Abstract class for all line operation.</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public abstract class AbstractLineOperation extends AbstractOperation implements ILineOperation { protected final Map<RuleParam, ParamValue> params; /** * Constructor * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public AbstractLineOperation(Map<RuleParam, ParamValue> params) { super(params); } }
small change
src/main/java/innovimax/mixthem/operation/AbstractLineOperation.java
small change
<ide><path>rc/main/java/innovimax/mixthem/operation/AbstractLineOperation.java <ide> */ <ide> public abstract class AbstractLineOperation extends AbstractOperation implements ILineOperation { <ide> <del> protected final Map<RuleParam, ParamValue> params; <del> <ide> /** <ide> * Constructor <ide> * @param params The list of parameters (maybe empty)
Java
mit
50217801fc8648a243cf7d311db6aee201dbe649
0
MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests
package us.kbase.jgiintegration.common; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import us.kbase.common.test.TestException; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** This class represents a JGI organism page and allows performing * operations - primarily selecting files and pushing them to KBase - on that * page. * @author [email protected] * */ public class JGIOrganismPage { private final static String JGI_SIGN_ON = "https://signon.jgi.doe.gov/signon"; private final static String JGI_ORG_PAGE_SUFFIX = "/pages/dynamicOrganismDownload.jsf?organism="; private final static URL JGI_ORG_PAGE_DEFAULT; static { try { JGI_ORG_PAGE_DEFAULT = new URL("http://genomeportal.jgi.doe.gov"); } catch (MalformedURLException mue) { throw new RuntimeException("You big dummy", mue); } } private final String organismCode; private HtmlPage page; private final Set<JGIFileLocation> selected = new HashSet<JGIFileLocation>(); /** Construct a new organism page using the default JGI portal url. * @param client the client to use to connect to the page. * @param organismCode the JGI organism code. * @param JGIuser the username for the JGI user that will sign in to JGI. * Set as null to skip login. * @param JGIpwd the password for the JGI user. * @throws Exception if an exception occurs. */ public JGIOrganismPage( WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { this(JGI_ORG_PAGE_DEFAULT, client, organismCode, JGIuser, JGIpwd); } /** Construct a new organism page. * @param portalURL the URL of the JGI genome portal. * @param client the client to use to connect to the page. * @param organismCode the JGI organism code. * @param JGIuser the username for the JGI user that will sign in to JGI. * Set as null to skip login. * @param JGIpwd the password for the JGI user. * @throws Exception if an exception occurs. */ public JGIOrganismPage( URL portalURL, WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { super(); URI jgiOrgPage = portalURL.toURI().resolve(JGI_ORG_PAGE_SUFFIX); if (JGIuser == null) { System.out.println("Skipping JGI login, user is null"); } else { System.out.println(String.format("Signing on to JGI at %s...", new Date())); signOnToJGI((HtmlPage) client.getPage(JGI_SIGN_ON), JGIuser, JGIpwd); System.out.println(String.format("Signed on to JGI at %s.", new Date())); } System.out.println(String.format("Opening %s page at %s... ", organismCode, new Date())); this.organismCode = organismCode; page = loadOrganismPage(jgiOrgPage, client, organismCode); checkPermissionOk(); waitForPageToLoad(); //TODO try and remove this with improved page load Thread.sleep(5000); //this seems to be necessary for tests to pass, no idea why System.out.println(String.format( "Opened %s page at %s, %s characters.", organismCode, new Date(), page.asXml().length())); closePushedFilesDialog(false); } private void waitForPageToLoad() throws InterruptedException { int timeoutSec = 60; waitForGlobusButtonLoad(timeoutSec, "Globus button"); waitForXPathLoad(timeoutSec, "//input[contains(@class, 'pushToKbaseClass')]", "PtKB button"); waitForXPathLoad(timeoutSec, "//div[@class='rich-tree-node-children']", "file tree"); //TODO remove if can't be made to work // waitForFileTree(timeoutSec, "file tree opacity"); } private void waitForGlobusButtonLoad(int timeoutSec, String name) throws InterruptedException { Long startNanos = System.nanoTime(); DomNode btn = getGlobusButton(); while (btn == null) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); btn = getGlobusButton(); System.out.println("waiting on " + name +" load at " + new Date()); } } private DomNode getGlobusButton() { DomElement fileTreePanel = page.getElementById( "downloadForm:fileTreePanel"); DomNode globusbutton = null; try { globusbutton = fileTreePanel .getFirstChild() //rich_panel no_frame .getFirstChild() //rich-panel-body .getFirstChild() //together .getFirstChild(); //button } catch (NullPointerException npe) { // not here yet } return globusbutton; } private void waitForFileTree(int timeoutSec, String name) throws InterruptedException { Long startNanos = System.nanoTime(); DomElement ajax = page.getElementById("ALL_ajax_div"); String style = ajax.getAttribute("style"); System.out.println("Ajax style: " + style); while(!style.equals("opacity: 1;")) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); style = ajax.getAttribute("style"); System.out.println("waiting on " + name +" load at " + new Date()); } } private void waitForXPathLoad(int timeoutSec, String xpath, String name) throws InterruptedException { List<HtmlElement> elements = getElementsByXPath(xpath); Long startNanos = System.nanoTime(); while (elements.isEmpty()) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); elements = getElementsByXPath(xpath); System.out.println("waiting on " + name +" load at " + new Date()); } //TODO remove this printing code when debugging complete System.out.println("----- " + xpath + ", name: " + name + " ------"); int count = 1; for (Object e: elements) { System.out.println("--- " + count + " ---"); count++; if (e instanceof HtmlElement) { System.out.println(((HtmlElement)e).asXml()); } else { System.out.println(e); } } System.out.println("--- printed " + (count -1 ) + " ---"); } private List<HtmlElement> getElementsByXPath(String xpath) { List<?> elements = page.getByXPath(xpath); List<HtmlElement> ret = new LinkedList<HtmlElement>(); for (Object e: elements) { HtmlElement el = (HtmlElement) e; if (el.isDisplayed()) { ret.add(el); } } return ret; } private void checkPermissionOk() throws JGIPermissionsException { List<?> filetree = page.getByXPath("//div[@class='warning']"); if (!filetree.isEmpty()) { DomElement e = (DomElement) filetree.get(0); if (e.getTextContent().contains("you do not have permission")) { throw new JGIPermissionsException( "No permission for organism " + organismCode); } } } private HtmlPage loadOrganismPage(URI jgiOrgPage, WebClient client, String organismCode) throws Exception { //This exception does not affect user experience or functionality //at all and occurs rather frequently, so we ignore it String acceptableExceptionContents = "https://issues.jgi-psf.org/rest/collectors/1.0/configuration/trigger/4c7588ab?os_authType=none&callback=trigger_4c7588ab"; HtmlPage page = null; while (page == null) { try { page = client.getPage(jgiOrgPage + organismCode); } catch (ScriptException se) { if (se.getMessage().contains( acceptableExceptionContents)) { System.out.println("Ignoring exception " + se); } else { throw se; } } } return page; } private void signOnToJGI(HtmlPage signonPage, String user, String password) throws IOException, MalformedURLException { assertThat("Signon title ok", signonPage.getTitleText(), is("JGI Single Sign On")); try { signonPage.getHtmlElementById("highlight-me"); fail("logged in already"); } catch (ElementNotFoundException enfe) { //we're all good } //login form has no name, which is the only way to get a specific form List<HtmlForm> forms = signonPage.getForms(); assertThat("1 form on login page", forms.size(), is(1)); HtmlForm form = forms.get(0); form.getInputByName("login").setValueAttribute(user); form.getInputByName("password").setValueAttribute(password); HtmlPage loggedIn = form.getInputByName("commit").click(); HtmlDivision div = loggedIn.getHtmlElementById("highlight-me"); assertThat("signed in correctly", div.getTextContent().trim(), is("You have signed in successfully.")); } /** Returns the url for an organism page. * @param portalURL the url of the JGI genome portal. * @param organism the JGI organism code. * @return the URL of the page for the organism. */ public static String getURLforOrganism(URL portalURL, String organism) { return portalURL + JGI_ORG_PAGE_SUFFIX + organism; } /** Returns the organism code for this page. * @return the organism code for this page. */ public String getOrganismCode() { return organismCode; } /** Prints the contents of this web page as xml to standard out. * */ public void printPageToStdout() { System.out.println(page.asXml()); } /** Get the names of the first level filegroups in this page. * @return the names of the first level filegroups. */ public List<String> listFileGroups() { List<?> filetree = page.getByXPath("//div[@class='rich-tree ']"); if (filetree.isEmpty()) { System.out.println("No rich tree found in page. Current page:\n" + page.asXml()); throw new TestException("No rich tree found in page"); } DomElement ft = (DomElement) filetree.get(0); DomElement fileContainer = (DomElement) ft .getFirstChild() .getChildNodes().get(2); List<String> ret = new LinkedList<String>(); for (DomNode child: fileContainer.getChildNodes()) { DomElement echild = (DomElement) child; if (echild.getTagName().equals("table")) { DomNodeList<HtmlElement> group = echild.getElementsByTagName("b"); for (HtmlElement e: group) { ret.add(e.getTextContent()); } } } return ret; } /** List the files in a file group. This function only works for top * level filegroups. * @param fileGroup the name of the file group. * @return the list of files in the file group. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public List<String> listFiles(String fileGroup) throws IOException, InterruptedException { DomElement fg = openFileGroup(fileGroup); List<HtmlElement> names = fg.getElementsByTagName("b"); List<String> ret = new LinkedList<String>(); for (HtmlElement he: names) { ret.add(he.getTextContent()); } return ret; } /** Select a file on the organism page (e.g. check the checkbox). * @param file the file to select. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void selectFile(JGIFileLocation file) throws IOException, InterruptedException { selectFile(file, true); } /** Select or unselect a file on the organism page (e.g. check or uncheck * the checkbox). * @param file the file to select or unselect. * @param select true to select the file, false to unselect. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void selectFile(JGIFileLocation file, boolean select) throws IOException, InterruptedException { //text element with the file group name String selstr = select ? "Select" : "Unselect"; System.out.println(String.format("%sing file %s from group %s", selstr, file.getFile(), file.getGroup())); DomElement fileText = findFile(file); HtmlCheckBoxInput filetoggle = (HtmlCheckBoxInput) ((DomElement) fileText .getParentNode() //i .getParentNode() //a .getParentNode() //span .getParentNode()) //td .getElementsByTagName("input").get(0); if (select == filetoggle.getCheckedAttribute().equals("checked")) { return; } this.page = filetoggle.click(); if (select) { selected.add(file); } else { selected.remove(file); } Thread.sleep(1000); //every click gets sent to the server System.out.println(String.format("%sed file %s from group %s.", selstr, file.getFile(), file.getGroup())); } private DomElement findFile(JGIFileLocation file) throws IOException, InterruptedException { DomElement fileGroup = openFileGroup(file.getGroup()); //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<HtmlElement> bold = fileGroup.getElementsByTagName("b"); for (HtmlElement de: bold) { if (file.getFile().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new NoSuchJGIFileException(String.format( "There is no file %s in file group %s for the organism %s", file.getFile(), file.getGroup(), organismCode)); } return selGroup; } private DomElement openFileGroup(String group) throws IOException, InterruptedException { int timeoutSec = 60; System.out.println(String.format("Opening file group %s at %s... ", group, new Date())); DomElement fileGroupText = findFileGroup(group); DomElement fileContainer = getFilesDivFromFilesGroup( fileGroupText); if (fileContainer.isDisplayed()) { System.out.println(String.format("File group %s already open.", group)); return fileContainer; } HtmlAnchor fileSetToggle = (HtmlAnchor) fileGroupText .getParentNode() //td .getPreviousSibling() //td folder icon .getPreviousSibling() //td toggle icon .getChildNodes().get(0) //div .getChildNodes().get(0); //a this.page = fileSetToggle.click(); Long startNanos = System.nanoTime(); while (!fileContainer.isDisplayed()) { fileGroupText = findFileGroup(group); fileContainer = getFilesDivFromFilesGroup(fileGroupText); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for file group %s to open after %s seconds, contents:\n%s", group, timeoutSec, fileContainer.asXml())); Thread.sleep(1000); } System.out.println(String.format("Opened file group %s at %s.", group, new Date())); return fileContainer; } /** Push the selected files to KBase. * @param user the KBase username of the user that is pushing the files. * @param pwd the password for the KBase user. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void pushToKBase(String user, String pwd) throws IOException, InterruptedException { System.out.println(String.format("Pushing files to KBase at %s...", new Date())); List<?> pushlist = page.getByXPath( "//input[contains(@class, 'pushToKbaseClass')]"); assertThat("only 1 pushToKbaseClass", pushlist.size(), is(1)); HtmlInput push = (HtmlInput) pushlist.get(0); this.page = push.click(); Thread.sleep(1000); // just in case, should be fast to create modal HtmlForm kbLogin = page.getFormByName("form"); //interesting id there kbLogin.getInputByName("user_id").setValueAttribute(user); kbLogin.getInputByName("password").setValueAttribute(pwd); HtmlAnchor loginButton = (HtmlAnchor) kbLogin .getParentNode() //p .getParentNode() //div .getNextSibling() //div .getFirstChild() //div .getChildNodes().get(1) //div .getChildNodes().get(1); //a this.page = loginButton.click(); checkPushedFiles(); closePushedFilesDialog(true); Set<JGIFileLocation> fixconcurrent = new HashSet<JGIFileLocation>(selected); for (JGIFileLocation file: fixconcurrent) { selectFile(file, false); //reset all toggles to unselected state } System.out.println(String.format("Finished push to KBase at %s.", new Date())); } private void closePushedFilesDialog(boolean failIfClosedNow) throws IOException, InterruptedException { HtmlElement resDialogDiv = (HtmlElement) page.getElementById( "downloadForm:showFilesPushedToKbaseContentTable"); if (resDialogDiv == null) { System.out.println("couldn't find div for post-push dialog. Page:"); System.out.println(page.asXml()); fail("The post-push dialog div is not in the page as expected"); } if (failIfClosedNow) { assertThat("result dialog open", resDialogDiv.isDisplayed(), is(true)); } else { if (!resDialogDiv.isDisplayed()) { return; } } HtmlInput ok = (HtmlInput) resDialogDiv .getFirstChild() //tbody .getFirstChild() //tr .getFirstChild() //td .getFirstChild() //div .getChildNodes().get(2) //div .getFirstChild(); //input page = ok.click(); Thread.sleep(2000); resDialogDiv = (HtmlElement) page.getElementById( "downloadForm:showFilesPushedToKbaseContentTable"); assertThat("Dialog closed", resDialogDiv.isDisplayed(), is(false)); } /** Get the workspace name associated with this organism page. * @param user the KBase username of the user that will push the files. * @return */ public String getWorkspaceName(String user) { List<?> orgNames = page.getByXPath("//div[@class='organismName']"); assertThat("only 1 organismName class", orgNames.size(), is(1)); DomNode orgName = (DomNode) orgNames.get(0); return orgName.getTextContent() .replace(" ", "_") .replace("-", "") .replace(".", "") .replace("/", "") + '_' + user; } private void checkPushedFiles() throws InterruptedException { // make this configurable per test? //may need to be longer for tape files Set<String> filesFound = getPushedFileList("acceptedFiles"); Set<String> filesRejected = getPushedFileList("rejectedFiles"); Set<String> filesExpected = new HashSet<String>(); Set<String> rejectedExpected = new HashSet<String>(); for (JGIFileLocation file: selected) { if (file.isExpectedRejection()) { rejectedExpected.add(file.getFile()); } else { filesExpected.add(file.getFile()); } } checkPushedFileSet("Expected", filesExpected, filesFound); checkPushedFileSet("Expected rejected ", filesRejected, rejectedExpected); } private void checkPushedFileSet(String desc, Set<String> filesExpected, Set<String> filesFound) { if (!filesFound.equals(filesExpected)) { System.out.println(desc + " files for push did not match actual:"); System.out.println("Expected: " + filesExpected); System.out.println("Actual: " + filesFound); System.out.println("KBase result dialog:"); System.out.println(getKBaseResultDialog().asXml()); fail(desc + " files for push did not match actual: " + filesExpected + " vs. " + filesFound); } } private Set<String> getPushedFileList(String elementID) throws InterruptedException { int timeoutSec = 60; HtmlElement resDialogDiv = (HtmlElement) page.getElementById(elementID); DomNode bodyParent = getKBaseResultDialog(); Long startNanos = System.nanoTime(); while (!bodyParent.isDisplayed()) { checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for files to push to Kbase after %s seconds", timeoutSec)); Thread.sleep(1000); } String[] splDialog = resDialogDiv.getTextContent().split("\n"); Set<String> filesFound = new HashSet<String>(); for (int i = 0; i < splDialog.length; i++) { if (splDialog[i].length() > 0) { filesFound.add(splDialog[i]); } } return filesFound; } private DomNode getKBaseResultDialog() { HtmlElement resDialogDiv = (HtmlElement) page.getElementById("supportedFileTypes"); return resDialogDiv.getParentNode(); //div modal-body } private DomElement getFilesDivFromFilesGroup(DomElement selGroup) { return (DomElement) selGroup .getParentNode() //td .getParentNode() //tr .getParentNode() //tbody .getParentNode() //table .getNextSibling(); //div below table } private DomElement findFileGroup(String group) { //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<DomElement> bold = page.getElementsByTagName("b"); for (DomElement de: bold) { if (group.equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { System.out.println(String.format( "There is no file group %s for the organism %s. Found bold tags:", group, organismCode)); for (DomElement de: bold) { System.out.println(de.asXml()); } System.out.println("Current page:"); System.out.println(page.asXml()); throw new NoSuchJGIFileGroupException(String.format( "There is no file group %s for the organism %s", group, organismCode)); } return selGroup; } private static void checkTimeout(Long startNanos, int timeoutSec, String message) { checkTimeout(startNanos, timeoutSec, message, null); } private static void checkTimeout(Long startNanos, int timeoutSec, String message, String printToStdOut) { //ugh if ((System.nanoTime() - startNanos) / 1000000000 > timeoutSec) { System.out.println(message); if (printToStdOut != null) { System.out.println(printToStdOut); } throw new TimeoutException(message); } } @SuppressWarnings("serial") public static class NoSuchJGIFileException extends RuntimeException { public NoSuchJGIFileException(String msg) { super(msg); } } @SuppressWarnings("serial") public static class NoSuchJGIFileGroupException extends RuntimeException { public NoSuchJGIFileGroupException(String msg) { super(msg); } } @SuppressWarnings("serial") public static class TimeoutException extends RuntimeException { public TimeoutException(String msg) { super(msg); } public TimeoutException(String msg, Throwable cause) { super(msg, cause); } } @SuppressWarnings("serial") public class JGIPermissionsException extends Exception { public JGIPermissionsException(String msg) { super(msg); } } }
src/us/kbase/jgiintegration/common/JGIOrganismPage.java
package us.kbase.jgiintegration.common; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import us.kbase.common.test.TestException; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** This class represents a JGI organism page and allows performing * operations - primarily selecting files and pushing them to KBase - on that * page. * @author [email protected] * */ public class JGIOrganismPage { private final static String JGI_SIGN_ON = "https://signon.jgi.doe.gov/signon"; private final static String JGI_ORG_PAGE_SUFFIX = "/pages/dynamicOrganismDownload.jsf?organism="; private final static URL JGI_ORG_PAGE_DEFAULT; static { try { JGI_ORG_PAGE_DEFAULT = new URL("http://genomeportal.jgi.doe.gov"); } catch (MalformedURLException mue) { throw new RuntimeException("You big dummy", mue); } } private final String organismCode; private HtmlPage page; private final Set<JGIFileLocation> selected = new HashSet<JGIFileLocation>(); /** Construct a new organism page using the default JGI portal url. * @param client the client to use to connect to the page. * @param organismCode the JGI organism code. * @param JGIuser the username for the JGI user that will sign in to JGI. * Set as null to skip login. * @param JGIpwd the password for the JGI user. * @throws Exception if an exception occurs. */ public JGIOrganismPage( WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { this(JGI_ORG_PAGE_DEFAULT, client, organismCode, JGIuser, JGIpwd); } /** Construct a new organism page. * @param portalURL the URL of the JGI genome portal. * @param client the client to use to connect to the page. * @param organismCode the JGI organism code. * @param JGIuser the username for the JGI user that will sign in to JGI. * Set as null to skip login. * @param JGIpwd the password for the JGI user. * @throws Exception if an exception occurs. */ public JGIOrganismPage( URL portalURL, WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { super(); URI jgiOrgPage = portalURL.toURI().resolve(JGI_ORG_PAGE_SUFFIX); if (JGIuser == null) { System.out.println("Skipping JGI login, user is null"); } else { System.out.println(String.format("Signing on to JGI at %s...", new Date())); signOnToJGI((HtmlPage) client.getPage(JGI_SIGN_ON), JGIuser, JGIpwd); System.out.println(String.format("Signed on to JGI at %s.", new Date())); } System.out.println(String.format("Opening %s page at %s... ", organismCode, new Date())); this.organismCode = organismCode; page = loadOrganismPage(jgiOrgPage, client, organismCode); checkPermissionOk(); waitForPageToLoad(); //TODO try and remove this with improved page load Thread.sleep(5000); //this seems to be necessary for tests to pass, no idea why System.out.println(String.format( "Opened %s page at %s, %s characters.", organismCode, new Date(), page.asXml().length())); closePushedFilesDialog(false); } private void waitForPageToLoad() throws InterruptedException { int timeoutSec = 20; waitForGlobusButtonLoad(timeoutSec, "Globus button"); waitForXPathLoad(timeoutSec, "//input[contains(@class, 'pushToKbaseClass')]", "PtKB button"); waitForXPathLoad(timeoutSec, "//div[@class='rich-tree-node-children']", "file tree"); //TODO remove if can't be made to work // waitForFileTree(timeoutSec, "file tree opacity"); } private void waitForGlobusButtonLoad(int timeoutSec, String name) throws InterruptedException { Long startNanos = System.nanoTime(); DomNode btn = getGlobusButton(); while (btn == null) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); btn = getGlobusButton(); System.out.println("waiting on " + name +" load at " + new Date()); } } private DomNode getGlobusButton() { DomElement fileTreePanel = page.getElementById( "downloadForm:fileTreePanel"); DomNode globusbutton = null; try { globusbutton = fileTreePanel .getFirstChild() //rich_panel no_frame .getFirstChild() //rich-panel-body .getFirstChild() //together .getFirstChild(); //button } catch (NullPointerException npe) { // not here yet } return globusbutton; } private void waitForFileTree(int timeoutSec, String name) throws InterruptedException { Long startNanos = System.nanoTime(); DomElement ajax = page.getElementById("ALL_ajax_div"); String style = ajax.getAttribute("style"); System.out.println("Ajax style: " + style); while(!style.equals("opacity: 1;")) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); style = ajax.getAttribute("style"); System.out.println("waiting on " + name +" load at " + new Date()); } } private void waitForXPathLoad(int timeoutSec, String xpath, String name) throws InterruptedException { List<HtmlElement> elements = getElementsByXPath(xpath); Long startNanos = System.nanoTime(); while (elements.isEmpty()) { Thread.sleep(1000); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for %s to load after %s seconds.", name, timeoutSec), "Page contents\n" + page.asXml()); elements = getElementsByXPath(xpath); System.out.println("waiting on " + name +" load at " + new Date()); } //TODO remove this printing code when debugging complete System.out.println("----- " + xpath + ", name: " + name + " ------"); int count = 1; for (Object e: elements) { System.out.println("--- " + count + " ---"); count++; if (e instanceof HtmlElement) { System.out.println(((HtmlElement)e).asXml()); } else { System.out.println(e); } } System.out.println("--- printed " + (count -1 ) + " ---"); } private List<HtmlElement> getElementsByXPath(String xpath) { List<?> elements = page.getByXPath(xpath); List<HtmlElement> ret = new LinkedList<HtmlElement>(); for (Object e: elements) { HtmlElement el = (HtmlElement) e; if (el.isDisplayed()) { ret.add(el); } } return ret; } private void checkPermissionOk() throws JGIPermissionsException { List<?> filetree = page.getByXPath("//div[@class='warning']"); if (!filetree.isEmpty()) { DomElement e = (DomElement) filetree.get(0); if (e.getTextContent().contains("you do not have permission")) { throw new JGIPermissionsException( "No permission for organism " + organismCode); } } } private HtmlPage loadOrganismPage(URI jgiOrgPage, WebClient client, String organismCode) throws Exception { //This exception does not affect user experience or functionality //at all and occurs rather frequently, so we ignore it String acceptableExceptionContents = "https://issues.jgi-psf.org/rest/collectors/1.0/configuration/trigger/4c7588ab?os_authType=none&callback=trigger_4c7588ab"; HtmlPage page = null; while (page == null) { try { page = client.getPage(jgiOrgPage + organismCode); } catch (ScriptException se) { if (se.getMessage().contains( acceptableExceptionContents)) { System.out.println("Ignoring exception " + se); } else { throw se; } } } return page; } private void signOnToJGI(HtmlPage signonPage, String user, String password) throws IOException, MalformedURLException { assertThat("Signon title ok", signonPage.getTitleText(), is("JGI Single Sign On")); try { signonPage.getHtmlElementById("highlight-me"); fail("logged in already"); } catch (ElementNotFoundException enfe) { //we're all good } //login form has no name, which is the only way to get a specific form List<HtmlForm> forms = signonPage.getForms(); assertThat("1 form on login page", forms.size(), is(1)); HtmlForm form = forms.get(0); form.getInputByName("login").setValueAttribute(user); form.getInputByName("password").setValueAttribute(password); HtmlPage loggedIn = form.getInputByName("commit").click(); HtmlDivision div = loggedIn.getHtmlElementById("highlight-me"); assertThat("signed in correctly", div.getTextContent().trim(), is("You have signed in successfully.")); } /** Returns the url for an organism page. * @param portalURL the url of the JGI genome portal. * @param organism the JGI organism code. * @return the URL of the page for the organism. */ public static String getURLforOrganism(URL portalURL, String organism) { return portalURL + JGI_ORG_PAGE_SUFFIX + organism; } /** Returns the organism code for this page. * @return the organism code for this page. */ public String getOrganismCode() { return organismCode; } /** Prints the contents of this web page as xml to standard out. * */ public void printPageToStdout() { System.out.println(page.asXml()); } /** Get the names of the first level filegroups in this page. * @return the names of the first level filegroups. */ public List<String> listFileGroups() { List<?> filetree = page.getByXPath("//div[@class='rich-tree ']"); if (filetree.isEmpty()) { System.out.println("No rich tree found in page. Current page:\n" + page.asXml()); throw new TestException("No rich tree found in page"); } DomElement ft = (DomElement) filetree.get(0); DomElement fileContainer = (DomElement) ft .getFirstChild() .getChildNodes().get(2); List<String> ret = new LinkedList<String>(); for (DomNode child: fileContainer.getChildNodes()) { DomElement echild = (DomElement) child; if (echild.getTagName().equals("table")) { DomNodeList<HtmlElement> group = echild.getElementsByTagName("b"); for (HtmlElement e: group) { ret.add(e.getTextContent()); } } } return ret; } /** List the files in a file group. This function only works for top * level filegroups. * @param fileGroup the name of the file group. * @return the list of files in the file group. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public List<String> listFiles(String fileGroup) throws IOException, InterruptedException { DomElement fg = openFileGroup(fileGroup); List<HtmlElement> names = fg.getElementsByTagName("b"); List<String> ret = new LinkedList<String>(); for (HtmlElement he: names) { ret.add(he.getTextContent()); } return ret; } /** Select a file on the organism page (e.g. check the checkbox). * @param file the file to select. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void selectFile(JGIFileLocation file) throws IOException, InterruptedException { selectFile(file, true); } /** Select or unselect a file on the organism page (e.g. check or uncheck * the checkbox). * @param file the file to select or unselect. * @param select true to select the file, false to unselect. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void selectFile(JGIFileLocation file, boolean select) throws IOException, InterruptedException { //text element with the file group name String selstr = select ? "Select" : "Unselect"; System.out.println(String.format("%sing file %s from group %s", selstr, file.getFile(), file.getGroup())); DomElement fileText = findFile(file); HtmlCheckBoxInput filetoggle = (HtmlCheckBoxInput) ((DomElement) fileText .getParentNode() //i .getParentNode() //a .getParentNode() //span .getParentNode()) //td .getElementsByTagName("input").get(0); if (select == filetoggle.getCheckedAttribute().equals("checked")) { return; } this.page = filetoggle.click(); if (select) { selected.add(file); } else { selected.remove(file); } Thread.sleep(1000); //every click gets sent to the server System.out.println(String.format("%sed file %s from group %s.", selstr, file.getFile(), file.getGroup())); } private DomElement findFile(JGIFileLocation file) throws IOException, InterruptedException { DomElement fileGroup = openFileGroup(file.getGroup()); //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<HtmlElement> bold = fileGroup.getElementsByTagName("b"); for (HtmlElement de: bold) { if (file.getFile().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new NoSuchJGIFileException(String.format( "There is no file %s in file group %s for the organism %s", file.getFile(), file.getGroup(), organismCode)); } return selGroup; } private DomElement openFileGroup(String group) throws IOException, InterruptedException { int timeoutSec = 60; System.out.println(String.format("Opening file group %s at %s... ", group, new Date())); DomElement fileGroupText = findFileGroup(group); DomElement fileContainer = getFilesDivFromFilesGroup( fileGroupText); if (fileContainer.isDisplayed()) { System.out.println(String.format("File group %s already open.", group)); return fileContainer; } HtmlAnchor fileSetToggle = (HtmlAnchor) fileGroupText .getParentNode() //td .getPreviousSibling() //td folder icon .getPreviousSibling() //td toggle icon .getChildNodes().get(0) //div .getChildNodes().get(0); //a this.page = fileSetToggle.click(); Long startNanos = System.nanoTime(); while (!fileContainer.isDisplayed()) { fileGroupText = findFileGroup(group); fileContainer = getFilesDivFromFilesGroup(fileGroupText); checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for file group %s to open after %s seconds, contents:\n%s", group, timeoutSec, fileContainer.asXml())); Thread.sleep(1000); } System.out.println(String.format("Opened file group %s at %s.", group, new Date())); return fileContainer; } /** Push the selected files to KBase. * @param user the KBase username of the user that is pushing the files. * @param pwd the password for the KBase user. * @throws IOException if an IO exception occurs. * @throws InterruptedException if this function is interrupted while * sleeping. */ public void pushToKBase(String user, String pwd) throws IOException, InterruptedException { System.out.println(String.format("Pushing files to KBase at %s...", new Date())); List<?> pushlist = page.getByXPath( "//input[contains(@class, 'pushToKbaseClass')]"); assertThat("only 1 pushToKbaseClass", pushlist.size(), is(1)); HtmlInput push = (HtmlInput) pushlist.get(0); this.page = push.click(); Thread.sleep(1000); // just in case, should be fast to create modal HtmlForm kbLogin = page.getFormByName("form"); //interesting id there kbLogin.getInputByName("user_id").setValueAttribute(user); kbLogin.getInputByName("password").setValueAttribute(pwd); HtmlAnchor loginButton = (HtmlAnchor) kbLogin .getParentNode() //p .getParentNode() //div .getNextSibling() //div .getFirstChild() //div .getChildNodes().get(1) //div .getChildNodes().get(1); //a this.page = loginButton.click(); checkPushedFiles(); closePushedFilesDialog(true); Set<JGIFileLocation> fixconcurrent = new HashSet<JGIFileLocation>(selected); for (JGIFileLocation file: fixconcurrent) { selectFile(file, false); //reset all toggles to unselected state } System.out.println(String.format("Finished push to KBase at %s.", new Date())); } private void closePushedFilesDialog(boolean failIfClosedNow) throws IOException, InterruptedException { HtmlElement resDialogDiv = (HtmlElement) page.getElementById( "downloadForm:showFilesPushedToKbaseContentTable"); if (resDialogDiv == null) { System.out.println("couldn't find div for post-push dialog. Page:"); System.out.println(page.asXml()); fail("The post-push dialog div is not in the page as expected"); } if (failIfClosedNow) { assertThat("result dialog open", resDialogDiv.isDisplayed(), is(true)); } else { if (!resDialogDiv.isDisplayed()) { return; } } HtmlInput ok = (HtmlInput) resDialogDiv .getFirstChild() //tbody .getFirstChild() //tr .getFirstChild() //td .getFirstChild() //div .getChildNodes().get(2) //div .getFirstChild(); //input page = ok.click(); Thread.sleep(2000); resDialogDiv = (HtmlElement) page.getElementById( "downloadForm:showFilesPushedToKbaseContentTable"); assertThat("Dialog closed", resDialogDiv.isDisplayed(), is(false)); } /** Get the workspace name associated with this organism page. * @param user the KBase username of the user that will push the files. * @return */ public String getWorkspaceName(String user) { List<?> orgNames = page.getByXPath("//div[@class='organismName']"); assertThat("only 1 organismName class", orgNames.size(), is(1)); DomNode orgName = (DomNode) orgNames.get(0); return orgName.getTextContent() .replace(" ", "_") .replace("-", "") .replace(".", "") .replace("/", "") + '_' + user; } private void checkPushedFiles() throws InterruptedException { // make this configurable per test? //may need to be longer for tape files Set<String> filesFound = getPushedFileList("acceptedFiles"); Set<String> filesRejected = getPushedFileList("rejectedFiles"); Set<String> filesExpected = new HashSet<String>(); Set<String> rejectedExpected = new HashSet<String>(); for (JGIFileLocation file: selected) { if (file.isExpectedRejection()) { rejectedExpected.add(file.getFile()); } else { filesExpected.add(file.getFile()); } } checkPushedFileSet("Expected", filesExpected, filesFound); checkPushedFileSet("Expected rejected ", filesRejected, rejectedExpected); } private void checkPushedFileSet(String desc, Set<String> filesExpected, Set<String> filesFound) { if (!filesFound.equals(filesExpected)) { System.out.println(desc + " files for push did not match actual:"); System.out.println("Expected: " + filesExpected); System.out.println("Actual: " + filesFound); System.out.println("KBase result dialog:"); System.out.println(getKBaseResultDialog().asXml()); fail(desc + " files for push did not match actual: " + filesExpected + " vs. " + filesFound); } } private Set<String> getPushedFileList(String elementID) throws InterruptedException { int timeoutSec = 60; HtmlElement resDialogDiv = (HtmlElement) page.getElementById(elementID); DomNode bodyParent = getKBaseResultDialog(); Long startNanos = System.nanoTime(); while (!bodyParent.isDisplayed()) { checkTimeout(startNanos, timeoutSec, String.format( "Timed out waiting for files to push to Kbase after %s seconds", timeoutSec)); Thread.sleep(1000); } String[] splDialog = resDialogDiv.getTextContent().split("\n"); Set<String> filesFound = new HashSet<String>(); for (int i = 0; i < splDialog.length; i++) { if (splDialog[i].length() > 0) { filesFound.add(splDialog[i]); } } return filesFound; } private DomNode getKBaseResultDialog() { HtmlElement resDialogDiv = (HtmlElement) page.getElementById("supportedFileTypes"); return resDialogDiv.getParentNode(); //div modal-body } private DomElement getFilesDivFromFilesGroup(DomElement selGroup) { return (DomElement) selGroup .getParentNode() //td .getParentNode() //tr .getParentNode() //tbody .getParentNode() //table .getNextSibling(); //div below table } private DomElement findFileGroup(String group) { //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<DomElement> bold = page.getElementsByTagName("b"); for (DomElement de: bold) { if (group.equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { System.out.println(String.format( "There is no file group %s for the organism %s. Found bold tags:", group, organismCode)); for (DomElement de: bold) { System.out.println(de.asXml()); } System.out.println("Current page:"); System.out.println(page.asXml()); throw new NoSuchJGIFileGroupException(String.format( "There is no file group %s for the organism %s", group, organismCode)); } return selGroup; } private static void checkTimeout(Long startNanos, int timeoutSec, String message) { checkTimeout(startNanos, timeoutSec, message, null); } private static void checkTimeout(Long startNanos, int timeoutSec, String message, String printToStdOut) { //ugh if ((System.nanoTime() - startNanos) / 1000000000 > timeoutSec) { System.out.println(message); if (printToStdOut != null) { System.out.println(printToStdOut); } throw new TimeoutException(message); } } @SuppressWarnings("serial") public static class NoSuchJGIFileException extends RuntimeException { public NoSuchJGIFileException(String msg) { super(msg); } } @SuppressWarnings("serial") public static class NoSuchJGIFileGroupException extends RuntimeException { public NoSuchJGIFileGroupException(String msg) { super(msg); } } @SuppressWarnings("serial") public static class TimeoutException extends RuntimeException { public TimeoutException(String msg) { super(msg); } public TimeoutException(String msg, Throwable cause) { super(msg, cause); } } @SuppressWarnings("serial") public class JGIPermissionsException extends Exception { public JGIPermissionsException(String msg) { super(msg); } } }
Kick up the globus button load timeout The globus button load check seemed to help a lot, in the 1 test run so far eliminated all the other failure modes and reduced fails from >10 to 2. Those two failed for globus button load timeouts, which appear to take longer with the new site.
src/us/kbase/jgiintegration/common/JGIOrganismPage.java
Kick up the globus button load timeout
<ide><path>rc/us/kbase/jgiintegration/common/JGIOrganismPage.java <ide> } <ide> <ide> private void waitForPageToLoad() throws InterruptedException { <del> int timeoutSec = 20; <add> int timeoutSec = 60; <ide> waitForGlobusButtonLoad(timeoutSec, "Globus button"); <ide> waitForXPathLoad(timeoutSec, <ide> "//input[contains(@class, 'pushToKbaseClass')]",
Java
bsd-2-clause
3f54c3cbf9de9c7473ad110099b0925abec47cc7
0
scifio/scifio
// // Compression.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan and Eric Kjellman. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.awt.image.BufferedImage; import java.io.*; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import javax.imageio.ImageIO; /** * A utility class for handling various compression types. * * @author Curtis Rueden ctrueden at wisc.edu * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at cs.wisc.edu */ public final class Compression { // -- Constants -- // LZW compression codes protected static final int CLEAR_CODE = 256; protected static final int EOI_CODE = 257; // LZO compression codes private static final int LZO_OVERRUN = -6; // Base64 alphabet and codes private static final int FOURBYTE = 4; private static final byte PAD = (byte) '='; private static byte[] base64Alphabet = new byte[255]; private static byte[] lookupBase64Alphabet = new byte[255]; static { for (int i=0; i<255; i++) { base64Alphabet[i] = (byte) -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i=0; i<=25; i++) { lookupBase64Alphabet[i] = (byte) ('A' + i); } for (int i=26, j=0; i<=51; i++, j++) { lookupBase64Alphabet[i] = (byte) ('a' + j); } for (int i=52, j=0; i<=61; i++, j++) { lookupBase64Alphabet[i] = (byte) ('0' + j); } lookupBase64Alphabet[62] = (byte) '+'; lookupBase64Alphabet[63] = (byte) '/'; } /** Huffman tree for the Nikon decoder. */ private static final int[] NIKON_TREE = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12 }; // -- Constructor -- private Compression() { } // -- Compression methods -- /** * Encodes an image strip using the LZW compression method. * Adapted from the TIFF 6.0 Specification: * http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf (page 61) */ public static byte[] lzwCompress(byte[] input) { if (input == null || input.length == 0) return input; // initialize symbol table LZWTreeNode symbols = new LZWTreeNode(-1); symbols.initialize(); int nextCode = 258; int numBits = 9; BitWriter out = new BitWriter(); out.write(CLEAR_CODE, numBits); ByteVector omega = new ByteVector(); for (int i=0; i<input.length; i++) { byte k = input[i]; LZWTreeNode omegaNode = symbols.nodeFromString(omega); LZWTreeNode omegaKNode = omegaNode.getChild(k); if (omegaKNode != null) { // omega+k is in the symbol table omega.add(k); } else { out.write(omegaNode.getCode(), numBits); omega.add(k); symbols.addTableEntry(omega, nextCode++); omega.clear(); omega.add(k); if (nextCode == 512) numBits = 10; else if (nextCode == 1024) numBits = 11; else if (nextCode == 2048) numBits = 12; else if (nextCode == 4096) { out.write(CLEAR_CODE, numBits); symbols.initialize(); nextCode = 258; numBits = 9; } } } out.write(symbols.codeFromString(omega), numBits); out.write(EOI_CODE, numBits); return out.toByteArray(); } /** * Encodes a byte array using Base64 encoding. * Much of this code was adapted from the Apache Commons Codec source. */ public static byte[] base64Encode(byte[] input) { int dataBits = input.length * 8; int fewerThan24 = dataBits % 24; int numTriples = dataBits / 24; byte[] encoded = null; int encodedLength = 0; if (fewerThan24 != 0) encodedLength = (numTriples + 1) * 4; else encodedLength = numTriples * 4; encoded = new byte[encodedLength]; byte k, l, b1, b2, b3; int encodedIndex = 0; int dataIndex = 0; for (int i=0; i<numTriples; i++) { dataIndex = i * 3; b1 = input[dataIndex]; b2 = input[dataIndex + 1]; b3 = input[dataIndex + 2]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte v1 = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte v2 = ((b2 & -128) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte v3 = ((b3 & -128) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encoded[encodedIndex] = lookupBase64Alphabet[v1]; encoded[encodedIndex + 1] = lookupBase64Alphabet[v2 | (k << 4)]; encoded[encodedIndex + 2] = lookupBase64Alphabet[(l << 2) | v3]; encoded[encodedIndex + 3] = lookupBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; } dataIndex = numTriples * 3; if (fewerThan24 == 8) { b1 = input[dataIndex]; k = (byte) (b1 & 0x03); byte v = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encoded[encodedIndex] = lookupBase64Alphabet[v]; encoded[encodedIndex + 1] = lookupBase64Alphabet[k << 4]; encoded[encodedIndex + 2] = (byte) '='; encoded[encodedIndex + 3] = (byte) '='; } else if (fewerThan24 == 16) { b1 = input[dataIndex]; b2 = input[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte v1 = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte v2 = ((b2 & -128) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encoded[encodedIndex] = lookupBase64Alphabet[v1]; encoded[encodedIndex + 1] = lookupBase64Alphabet[v2 | (k << 4)]; encoded[encodedIndex + 2] = lookupBase64Alphabet[l << 2]; encoded[encodedIndex + 3] = (byte) '='; } return encoded; } // -- Decompression methods -- /** * Decodes an LZO-compressed array. * Adapted from LZO for Java, available at * http://www.oberhumer.com/opensource/lzo/ */ public static void lzoUncompress(byte[] src, int size, byte[] dst) throws FormatException { int ip = 0; int op = 0; int t = src[ip++] & 0xff; int mPos; if (t > 17) { t -= 17; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; if (t < 16) return; } loop: for (;; t = src[ip++] & 0xff) { if (t < 16) { if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 15 + (src[ip++] & 0xff); } t += 3; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; if (t < 16) { mPos = op - 0x801 - (t >> 2) - ((src[ip++] & 0xff) << 2); if (mPos < 0) { t = LZO_OVERRUN; break loop; } t = 3; do dst[op++] = dst[mPos++]; while (--t > 0); t = src[ip - 2] & 3; if (t == 0) continue; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; } } for (;; t = src[ip++] & 0xff) { if (t >= 64) { mPos = op - 1 - ((t >> 2) & 7) - ((src[ip++] & 0xff) << 3); t = (t >> 5) - 1; } else if (t >= 32) { t &= 31; if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 31 + (src[ip++] & 0xff); } mPos = op - 1 - ((src[ip++] & 0xff) >> 2); mPos -= ((src[ip++] & 0xff) << 6); } else if (t >= 16) { mPos = op - ((t & 8) << 11); t &= 7; if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 7 + (src[ip++] & 0xff); } mPos -= ((src[ip++] & 0xff) >> 2); mPos -= ((src[ip++] & 0xff) << 6); if (mPos == op) break loop; mPos -= 0x4000; } else { mPos = op - 1 - (t >> 2) - ((src[ip++] & 0xff) << 2); t = 0; } if (mPos < 0) { t = LZO_OVERRUN; break loop; } t += 2; do dst[op++] = dst[mPos++]; while (--t > 0); t = src[ip - 2] & 3; if (t == 0) break; do dst[op++] = src[ip++]; while (--t > 0); } } } /** Decodes an Adobe Deflate (Zip) compressed image strip. */ public static byte[] deflateUncompress(byte[] input) throws FormatException { try { Inflater inf = new Inflater(false); inf.setInput(input); InflaterInputStream i = new InflaterInputStream(new PipedInputStream(), inf); ByteVector bytes = new ByteVector(); byte[] buf = new byte[8192]; while (true) { int r = i.read(buf, 0, buf.length); if (r == -1) break; // eof bytes.add(buf, 0, r); } return bytes.toByteArray(); } catch (Exception e) { throw new FormatException("Error uncompressing " + "Adobe Deflate (ZLIB) compressed image strip.", e); } } /** * Decodes a PackBits (Macintosh RLE) compressed image. * Adapted from the TIFF 6.0 specification, page 42. */ public static byte[] packBitsUncompress(byte[] input) { // Written by Melissa Linkert linkert at cs.wisc.edu ByteVector output = new ByteVector(input.length); int pt = 0; while (pt < input.length) { byte n = input[pt++]; if (n >= 0) { // 0 <= n <= 127 int len = pt + n + 1 > input.length ? (input.length - pt) : (n + 1); output.add(input, pt, len); pt += len; } else if (n != -128) { // -127 <= n <= -1 if (pt >= input.length) break; int len = -n + 1; byte inp = input[pt++]; for (int i=0; i<len; i++) output.add(inp); } } return output.toByteArray(); } /** * Decodes an image strip using Nikon's compression algorithm (a variant on * Huffman coding). */ public static byte[] nikonUncompress(byte[] input) throws FormatException { BitWriter out = new BitWriter(input.length); BitBuffer bb = new BitBuffer(input); boolean eof = false; while (!eof) { boolean codeFound = false; int code = 0; int bitsRead = 0; while (!codeFound) { int bit = bb.getBits(1); if (bit == -1) { eof = true; break; } bitsRead++; code >>= 1; code += bit; for (int i=16; i<NIKON_TREE.length; i++) { if (code == NIKON_TREE[i]) { int ndx = i; int count = 0; while (ndx > 16) { ndx -= NIKON_TREE[count]; count++; } if (ndx < 16) count--; if (bitsRead == count + 1) { codeFound = true; i = NIKON_TREE.length; break; } } } } while (code > 0) { out.write(bb.getBits(1), 1); code--; } } byte[] b = out.toByteArray(); return b; } /** * Decodes an LZW-compressed image strip. * Adapted from the TIFF 6.0 Specification: * http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf (page 61) */ public static byte[] lzwUncompress(byte[] input) throws FormatException { // Written by Eric Kjellman egkjellman at wisc.edu // Modified by Wayne Rasband wsr at nih.gov if (input == null || input.length == 0) return input; byte[][] symbolTable = new byte[4096][1]; int bitsToRead = 9; int nextSymbol = 258; int code; int oldCode = -1; ByteVector out = new ByteVector(8192); BitBuffer bb = new BitBuffer(input); byte[] byteBuffer1 = new byte[16]; byte[] byteBuffer2 = new byte[16]; while (true) { code = bb.getBits(bitsToRead); if (code == EOI_CODE || code == -1) break; if (code == CLEAR_CODE) { // initialize symbol table for (int i = 0; i < 256; i++) symbolTable[i][0] = (byte) i; nextSymbol = 258; bitsToRead = 9; code = bb.getBits(bitsToRead); if (code == EOI_CODE || code == -1) break; out.add(symbolTable[code]); oldCode = code; } else { if (code < nextSymbol) { // code is in table out.add(symbolTable[code]); // add string to table ByteVector symbol = new ByteVector(byteBuffer1); try { symbol.add(symbolTable[oldCode]); } catch (ArrayIndexOutOfBoundsException a) { throw new FormatException("Sorry, old LZW codes not supported"); } symbol.add(symbolTable[code][0]); symbolTable[nextSymbol] = symbol.toByteArray(); //** oldCode = code; nextSymbol++; } else { // out of table ByteVector symbol = new ByteVector(byteBuffer2); symbol.add(symbolTable[oldCode]); symbol.add(symbolTable[oldCode][0]); byte[] outString = symbol.toByteArray(); out.add(outString); symbolTable[nextSymbol] = outString; //** oldCode = code; nextSymbol++; } if (nextSymbol == 511) bitsToRead = 10; if (nextSymbol == 1023) bitsToRead = 11; if (nextSymbol == 2047) bitsToRead = 12; } } return out.toByteArray(); } /** Decodes a JPEG-compressed image. */ public static byte[] jpegUncompress(byte[] input) throws IOException { BufferedImage b = ImageIO.read(new ByteArrayInputStream(input)); byte[][] buf = ImageTools.getBytes(b); byte[] rtn = new byte[buf.length * buf[0].length]; if (buf.length == 1) rtn = buf[0]; else { for (int i=0; i<buf.length; i++) { System.arraycopy(buf[i], 0, rtn, i*buf[0].length, buf[i].length); } } return rtn; } /** * Decodes a Base64 encoded String. * Much of this code was adapted from the Apache Commons Codec source. */ public static byte[] base64Decode(String s) throws FormatException { byte[] base64Data = s.getBytes(); if (base64Data.length == 0) return new byte[0]; int numberQuadruple = base64Data.length / FOURBYTE; byte[] decodedData = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; int encodedIndex = 0; int dataIndex = 0; int lastData = base64Data.length; while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; for (int i=0; i<numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } }
loci/formats/Compression.java
// // Compression.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan and Eric Kjellman. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.awt.image.BufferedImage; import java.io.*; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import javax.imageio.ImageIO; /** * A utility class for handling various compression types. * * @author Curtis Rueden ctrueden at wisc.edu * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at cs.wisc.edu */ public final class Compression { // -- Constants -- // LZW compression codes protected static final int CLEAR_CODE = 256; protected static final int EOI_CODE = 257; // LZO compression codes private static final int LZO_OVERRUN = -6; // Base64 alphabet and codes private static final int FOURBYTE = 4; private static final byte PAD = (byte) '='; private static byte[] base64Alphabet = new byte[255]; private static byte[] lookupBase64Alphabet = new byte[255]; static { for (int i=0; i<255; i++) { base64Alphabet[i] = (byte) -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i=0; i<=25; i++) { lookupBase64Alphabet[i] = (byte) ('A' + i); } for (int i=26, j=0; i<=51; i++, j++) { lookupBase64Alphabet[i] = (byte) ('a' + j); } for (int i=52, j=0; i<=61; i++, j++) { lookupBase64Alphabet[i] = (byte) ('0' + j); } lookupBase64Alphabet[62] = (byte) '+'; lookupBase64Alphabet[63] = (byte) '/'; } /** Huffman tree for the Nikon decoder. */ private static final int[] NIKON_TREE = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12 }; // -- Constructor -- private Compression() { } // -- Compression methods -- /** * Encodes an image strip using the LZW compression method. * Adapted from the TIFF 6.0 Specification: * http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf (page 61) */ public static byte[] lzwCompress(byte[] input) { if (input == null || input.length == 0) return input; // initialize symbol table LZWTreeNode symbols = new LZWTreeNode(-1); symbols.initialize(); int nextCode = 258; int numBits = 9; BitWriter out = new BitWriter(); out.write(CLEAR_CODE, numBits); ByteVector omega = new ByteVector(); for (int i=0; i<input.length; i++) { byte k = input[i]; LZWTreeNode omegaNode = symbols.nodeFromString(omega); LZWTreeNode omegaKNode = omegaNode.getChild(k); if (omegaKNode != null) { // omega+k is in the symbol table omega.add(k); } else { out.write(omegaNode.getCode(), numBits); omega.add(k); symbols.addTableEntry(omega, nextCode++); omega.clear(); omega.add(k); if (nextCode == 512) numBits = 10; else if (nextCode == 1024) numBits = 11; else if (nextCode == 2048) numBits = 12; else if (nextCode == 4096) { out.write(CLEAR_CODE, numBits); symbols.initialize(); nextCode = 258; numBits = 9; } } } out.write(symbols.codeFromString(omega), numBits); out.write(EOI_CODE, numBits); return out.toByteArray(); } /** * Encodes a byte array using Base64 encoding. * Much of this code was adapted from the Apache Commons Codec source. */ public static byte[] base64Encode(byte[] input) { int dataBits = input.length * 8; int fewerThan24 = dataBits % 24; int numTriples = dataBits / 24; byte[] encoded = null; int encodedLength = 0; if (fewerThan24 != 0) encodedLength = (numTriples + 1) * 4; else encodedLength = numTriples * 4; encoded = new byte[encodedLength]; byte k, l, b1, b2, b3; int encodedIndex = 0; int dataIndex = 0; for (int i=0; i<numTriples; i++) { dataIndex = i * 3; b1 = input[dataIndex]; b2 = input[dataIndex + 1]; b3 = input[dataIndex + 2]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte v1 = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte v2 = ((b2 & -128) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte v3 = ((b3 & -128) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encoded[encodedIndex] = lookupBase64Alphabet[v1]; encoded[encodedIndex + 1] = lookupBase64Alphabet[v2 | (k << 4)]; encoded[encodedIndex + 2] = lookupBase64Alphabet[(l << 2) | v3]; encoded[encodedIndex + 3] = lookupBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; } dataIndex = numTriples * 3; if (fewerThan24 == 8) { b1 = input[dataIndex]; k = (byte) (b1 & 0x03); byte v = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encoded[encodedIndex] = lookupBase64Alphabet[v]; encoded[encodedIndex + 1] = lookupBase64Alphabet[k << 4]; encoded[encodedIndex + 2] = (byte) '='; encoded[encodedIndex + 3] = (byte) '='; } else if (fewerThan24 == 16) { b1 = input[dataIndex]; b2 = input[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte v1 = ((b1 & -128) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte v2 = ((b2 & -128) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encoded[encodedIndex] = lookupBase64Alphabet[v1]; encoded[encodedIndex + 1] = lookupBase64Alphabet[v2 | (k << 4)]; encoded[encodedIndex + 2] = lookupBase64Alphabet[l << 2]; encoded[encodedIndex + 3] = (byte) '='; } return encoded; } // -- Decompression methods -- /** * Decodes an LZO-compressed array. * Adapted from LZO for Java, available at * http://www.oberhumer.com/opensource/lzo/ */ public static void lzoUncompress(byte[] src, int size, byte[] dst) throws FormatException { int ip = 0; int op = 0; int t = src[ip++] & 0xff; int mPos; if (t > 17) { t -= 17; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; if (t < 16) return; } loop: for (;; t = src[ip++] & 0xff) { if (t < 16) { if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 15 + (src[ip++] & 0xff); } t += 3; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; if (t < 16) { mPos = op - 0x801 - (t >> 2) - ((src[ip++] & 0xff) << 2); if (mPos < 0) { t = LZO_OVERRUN; break loop; } t = 3; do dst[op++] = dst[mPos++]; while (--t > 0); t = src[ip - 2] & 3; if (t == 0) continue; do dst[op++] = src[ip++]; while (--t > 0); t = src[ip++] & 0xff; } } for (;; t = src[ip++] & 0xff) { if (t >= 64) { mPos = op - 1 - ((t >> 2) & 7) - ((src[ip++] & 0xff) << 3); t = (t >> 5) - 1; } else if (t >= 32) { t &= 31; if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 31 + (src[ip++] & 0xff); } mPos = op - 1 - ((src[ip++] & 0xff) >> 2); mPos -= ((src[ip++] & 0xff) << 6); } else if (t >= 16) { mPos = op - ((t & 8) << 11); t &= 7; if (t == 0) { while (src[ip] == 0) { t += 255; ip++; } t += 7 + (src[ip++] & 0xff); } mPos -= ((src[ip++] & 0xff) >> 2); mPos -= ((src[ip++] & 0xff) << 6); if (mPos == op) break loop; mPos -= 0x4000; } else { mPos = op - 1 - (t >> 2) - ((src[ip++] & 0xff) << 2); t = 0; } if (mPos < 0) { t = LZO_OVERRUN; break loop; } t += 2; do dst[op++] = dst[mPos++]; while (--t > 0); t = src[ip - 2] & 3; if (t == 0) break; do dst[op++] = src[ip++]; while (--t > 0); } } } /** Decodes an Adobe Deflate (Zip) compressed image strip. */ public static byte[] deflateUncompress(byte[] input) throws FormatException { try { Inflater inf = new Inflater(false); inf.setInput(input); InflaterInputStream i = new InflaterInputStream(new PipedInputStream(), inf); ByteVector bytes = new ByteVector(); byte[] buf = new byte[8192]; while (true) { int r = i.read(buf, 0, buf.length); if (r == -1) break; // eof bytes.add(buf, 0, r); } return bytes.toByteArray(); } catch (Exception e) { throw new FormatException("Error uncompressing " + "Adobe Deflate (ZLIB) compressed image strip.", e); } } /** * Decodes a PackBits (Macintosh RLE) compressed image. * Adapted from the TIFF 6.0 specification, page 42. * @author Melissa Linkert linkert at cs.wisc.edu */ public static byte[] packBitsUncompress(byte[] input) { ByteVector output = new ByteVector(input.length); int pt = 0; while (pt < input.length) { byte n = input[pt++]; if (n >= 0) { // 0 <= n <= 127 int len = pt + n + 1 > input.length ? (input.length - pt) : (n + 1); output.add(input, pt, len); pt += len; } else if (n != -128) { // -127 <= n <= -1 if (pt >= input.length) break; int len = -n + 1; byte inp = input[pt++]; for (int i=0; i<len; i++) output.add(inp); } } return output.toByteArray(); } /** * Decodes an image strip using Nikon's compression algorithm (a variant on * Huffman coding). */ public static byte[] nikonUncompress(byte[] input) throws FormatException { BitWriter out = new BitWriter(input.length); BitBuffer bb = new BitBuffer(input); boolean eof = false; while (!eof) { boolean codeFound = false; int code = 0; int bitsRead = 0; while (!codeFound) { int bit = bb.getBits(1); if (bit == -1) { eof = true; break; } bitsRead++; code >>= 1; code += bit; for (int i=16; i<NIKON_TREE.length; i++) { if (code == NIKON_TREE[i]) { int ndx = i; int count = 0; while (ndx > 16) { ndx -= NIKON_TREE[count]; count++; } if (ndx < 16) count--; if (bitsRead == count + 1) { codeFound = true; i = NIKON_TREE.length; break; } } } } while (code > 0) { out.write(bb.getBits(1), 1); code--; } } byte[] b = out.toByteArray(); return b; } /** * Decodes an LZW-compressed image strip. * Adapted from the TIFF 6.0 Specification: * http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf (page 61) * @author Eric Kjellman egkjellman at wisc.edu * @author Wayne Rasband wsr at nih.gov */ public static byte[] lzwUncompress(byte[] input) throws FormatException { if (input == null || input.length == 0) return input; byte[][] symbolTable = new byte[4096][1]; int bitsToRead = 9; int nextSymbol = 258; int code; int oldCode = -1; ByteVector out = new ByteVector(8192); BitBuffer bb = new BitBuffer(input); byte[] byteBuffer1 = new byte[16]; byte[] byteBuffer2 = new byte[16]; while (true) { code = bb.getBits(bitsToRead); if (code == EOI_CODE || code == -1) break; if (code == CLEAR_CODE) { // initialize symbol table for (int i = 0; i < 256; i++) symbolTable[i][0] = (byte) i; nextSymbol = 258; bitsToRead = 9; code = bb.getBits(bitsToRead); if (code == EOI_CODE || code == -1) break; out.add(symbolTable[code]); oldCode = code; } else { if (code < nextSymbol) { // code is in table out.add(symbolTable[code]); // add string to table ByteVector symbol = new ByteVector(byteBuffer1); try { symbol.add(symbolTable[oldCode]); } catch (ArrayIndexOutOfBoundsException a) { throw new FormatException("Sorry, old LZW codes not supported"); } symbol.add(symbolTable[code][0]); symbolTable[nextSymbol] = symbol.toByteArray(); //** oldCode = code; nextSymbol++; } else { // out of table ByteVector symbol = new ByteVector(byteBuffer2); symbol.add(symbolTable[oldCode]); symbol.add(symbolTable[oldCode][0]); byte[] outString = symbol.toByteArray(); out.add(outString); symbolTable[nextSymbol] = outString; //** oldCode = code; nextSymbol++; } if (nextSymbol == 511) bitsToRead = 10; if (nextSymbol == 1023) bitsToRead = 11; if (nextSymbol == 2047) bitsToRead = 12; } } return out.toByteArray(); } /** Decodes a JPEG-compressed image. */ public static byte[] jpegUncompress(byte[] input) throws IOException { BufferedImage b = ImageIO.read(new ByteArrayInputStream(input)); byte[][] buf = ImageTools.getBytes(b); byte[] rtn = new byte[buf.length * buf[0].length]; if (buf.length == 1) rtn = buf[0]; else { for (int i=0; i<buf.length; i++) { System.arraycopy(buf[i], 0, rtn, i*buf[0].length, buf[i].length); } } return rtn; } /** * Decodes a Base64 encoded String. * Much of this code was adapted from the Apache Commons Codec source. */ public static byte[] base64Decode(String s) throws FormatException { byte[] base64Data = s.getBytes(); if (base64Data.length == 0) return new byte[0]; int numberQuadruple = base64Data.length / FOURBYTE; byte[] decodedData = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; int encodedIndex = 0; int dataIndex = 0; int lastData = base64Data.length; while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; for (int i=0; i<numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } }
Remove illegal @author tags in methods.
loci/formats/Compression.java
Remove illegal @author tags in methods.
<ide><path>oci/formats/Compression.java <ide> /** <ide> * Decodes a PackBits (Macintosh RLE) compressed image. <ide> * Adapted from the TIFF 6.0 specification, page 42. <del> * @author Melissa Linkert linkert at cs.wisc.edu <ide> */ <ide> public static byte[] packBitsUncompress(byte[] input) { <add> // Written by Melissa Linkert linkert at cs.wisc.edu <ide> ByteVector output = new ByteVector(input.length); <ide> int pt = 0; <ide> while (pt < input.length) { <ide> * Decodes an LZW-compressed image strip. <ide> * Adapted from the TIFF 6.0 Specification: <ide> * http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf (page 61) <del> * @author Eric Kjellman egkjellman at wisc.edu <del> * @author Wayne Rasband wsr at nih.gov <ide> */ <ide> public static byte[] lzwUncompress(byte[] input) throws FormatException { <add> // Written by Eric Kjellman egkjellman at wisc.edu <add> // Modified by Wayne Rasband wsr at nih.gov <ide> if (input == null || input.length == 0) return input; <ide> <ide> byte[][] symbolTable = new byte[4096][1];
Java
lgpl-2.1
4139a5794da375b94281a7c968632a5abe8cc4ac
0
skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/wildcat,skyvers/wildcat
package org.skyve.impl.util; import java.io.Serializable; import java.net.URL; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Logger; import org.hibernate.proxy.HibernateProxy; import org.hibernate.util.SerializationHelper; import org.skyve.CORE; import org.skyve.domain.Bean; import org.skyve.domain.messages.DomainException; import org.skyve.impl.bind.BindUtil; import org.skyve.impl.domain.AbstractPersistentBean; import org.skyve.impl.metadata.model.document.AssociationImpl; import org.skyve.impl.metadata.model.document.field.LengthField; import org.skyve.impl.persistence.AbstractPersistence; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.metadata.model.document.Association.AssociationType; import org.skyve.metadata.model.document.Collection; import org.skyve.metadata.model.document.Collection.CollectionType; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Reference; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.User; import org.skyve.util.BeanVisitor; import org.skyve.impl.util.UtilImpl; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; public class UtilImpl { /** * Disallow instantiation */ private UtilImpl() { // no-op } public static boolean XML_TRACE = true; public static boolean HTTP_TRACE = false; public static boolean QUERY_TRACE = false; public static boolean COMMAND_TRACE = false; public static boolean FACES_TRACE = false; public static boolean SQL_TRACE = false; public static boolean CONTENT_TRACE = false; public static boolean SECURITY_TRACE = false; public static boolean BIZLET_TRACE = false; public static boolean DIRTY_TRACE = false; public static boolean PRETTY_SQL_OUTPUT = false; public static final Logger LOGGER = Logger.getLogger("SKYVE"); // This is set in the web.xml but defaults to windows // as a dev environment for design time and generation gear public static String CONTENT_DIRECTORY = "/_/Apps/content/"; // The cron expression to use to fire off the content garbage collection // Defaults to run at 7 past the hour every hour. public static String CONTENT_GC_CRON = "0 7 0/1 1/1 * ? *"; // Should the attachments be stored on the file system or inline. public static boolean CONTENT_FILE_STORAGE = true; // This is set in web.xml and should only be used when the APP server in use // doesn't allow us to get the absolute path of a resource - jboss 4.0.5.GA, WebLogic or any zipped deployment public static String APPS_JAR_DIRECTORY; public static boolean DEV_MODE = false; // If it is null, then the login infrastructure will prompt for the customer name. // If it is set, the customer will be set to that value always. // This property is also used for single sign on purposes. public static String CUSTOMER = null; // eg https://www.bizhub.com.au public static String SERVER_URL = null; // eg /bizhub/web public static String SKYVE_CONTEXT = null; // eg /init.biz public static String HOME_URI = null; // This is the path on the server file system of the web context root public static String SKYVE_CONTEXT_REAL_PATH = null; // Implementations of Key SKYVE classes public static String SKYVE_REPOSITORY_CLASS = null; public static String SKYVE_PERSISTENCE_CLASS = null; public static String SKYVE_CONTENT_MANAGER_CLASS = null; // The directory used for temp files for file uploads etc public static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir"); public static boolean USING_JPA = false; // For conversations cache public static int MAX_CONVERSATIONS_IN_MEMORY = 1000; public static int CONVERSATION_EVICTION_TIME_MINUTES = 60; // For database public static String DATASOURCE = null; public static String STANDALONE_DATABASE_JDBC_DRIVER = null; public static String STANDALONE_DATABASE_CONNECTION_URL = null; public static String STANDALONE_DATABASE_USERNAME = null; public static String STANDALONE_DATABASE_PASSWORD = null; public static String DIALECT = "MySQL5InnoDBDialect"; public static boolean DDL_SYNC = true; // For E-Mail public static String SMTP = null; public static String SMTP_PORT = null; public static String SMTP_UID = null; public static String SMTP_PWD = null; public static String SMTP_SENDER = null; // used to intercept all email and send to this test email account public static String SMTP_TEST_RECIPIENT = null; // used to switch whether to send an email or not - false to actually send the email public static boolean SMTP_TEST_BOGUS_SEND = false; // Password hash algorithm public static String PASSWORD_HASHING_ALGORITHM = "MD5"; // For versioning javascript for web site public static final String JAVASCRIPT_FILE_VERSION = "20160505"; public static final String SKYVE_VERSION = "20160505"; public static final String SMART_CLIENT_DIR = "isomorphic110"; private static String absoluteBasePath; public static String getAbsoluteBasePath() { if (absoluteBasePath == null) { if (APPS_JAR_DIRECTORY != null) { absoluteBasePath = APPS_JAR_DIRECTORY; } else { URL url = Thread.currentThread().getContextClassLoader().getResource("schemas/common.xsd"); absoluteBasePath = url.getPath(); absoluteBasePath = absoluteBasePath.substring(0, absoluteBasePath.length() - 18); // remove schemas/common.xsd absoluteBasePath = absoluteBasePath.replace('\\', '/'); } } return absoluteBasePath; } @SuppressWarnings("unchecked") public static final <T extends Serializable> T cloneBySerialization(T object) { return (T) SerializationHelper.clone(object); // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // new ObjectOutputStream(baos).writeObject(object); // ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); // return (T) ois.readObject(); // } // catch (Exception e) { // throw new IllegalArgumentException(e); // } } public static final <T extends Serializable> T cloneToTransientBySerialization(T object) throws Exception { if (object instanceof List<?>) { for (Object element : (List<?>) object) { if (element instanceof AbstractPersistentBean) { populateFully((AbstractPersistentBean) object); } } } else if (object instanceof AbstractPersistentBean) { populateFully((AbstractPersistentBean) object); } T result = cloneBySerialization(object); setTransient(result); return result; } /** * Recurse the bean ensuring that everything is touched and loaded from the database. * * @param bean The bean to load. * @throws DomainException * @throws MetaDataException */ public static void populateFully(final Bean bean) throws DomainException, MetaDataException { User user = CORE.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); // Ensure that everything is loaded new BeanVisitor(false, true, false) { @Override protected boolean accept(String binding, Document documentAccepted, Document owningDocument, Relation owningRelation, Bean beanAccepted) throws DomainException, MetaDataException { // do nothing - just visiting loads the instance from the database try { if (beanAccepted != bean) { if (beanAccepted instanceof HibernateProxy) { BindUtil.set(bean, binding, ((HibernateProxy) beanAccepted).getHibernateLazyInitializer().getImplementation()); } } } catch (Exception e) { throw new DomainException(e); } return true; } }.visit(document, bean, customer); } /** * Recurse a bean to determine if anything has changed */ private static class ChangedBeanVisitor extends BeanVisitor { private boolean changed = false; private ChangedBeanVisitor() { // Don't check inverses as they aren't cascaded anyway super(false, false, false); } @Override protected boolean accept(String binding, Document documentAccepted, Document owningDocument, Relation owningRelation, Bean beanAccepted) throws DomainException, MetaDataException { if (beanAccepted.isChanged()) { changed = true; if (UtilImpl.DIRTY_TRACE) UtilImpl.LOGGER.info("UtilImpl.hasChanged(): Bean " + beanAccepted.toString() + " with binding " + binding + " is DIRTY"); return false; } return true; } boolean isChanged() { return changed; } } /** * Recurse the bean to determine if anything has changed. * * @param bean The bean to test. * @return if the bean, its collections or its aggregated beans have mutated or not * @throws DomainException * @throws MetaDataException */ public static boolean hasChanged(Bean bean) throws DomainException, MetaDataException { User user = CORE.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); @SuppressWarnings("synthetic-access") ChangedBeanVisitor cbv = new ChangedBeanVisitor(); cbv.visit(document, bean, customer); return cbv.isChanged(); } /** * Utility method that tries to properly initialise the persistence layer proxies used by lazy loading. * * @param <T> * @param possibleProxy The possible proxy * @return the resolved proxy or possibleProxy */ @SuppressWarnings("unchecked") public static <T> T deproxy(T possibleProxy) throws ClassCastException { if (possibleProxy instanceof HibernateProxy) { return (T) ((HibernateProxy) possibleProxy).getHibernateLazyInitializer().getImplementation(); } return possibleProxy; } public static void setTransient(Object object) throws Exception { if (object instanceof List<?>) { List<?> list = (List<?>) object; for (Object element : list) { setTransient(element); } } else if (object instanceof AbstractPersistentBean) { AbstractPersistentBean bean = (AbstractPersistentBean) object; bean.setBizId(UUID.randomUUID().toString()); bean.setBizLock(null); bean.setBizVersion(null); // set references transient if applicable Customer customer = AbstractPersistence.get().getUser().getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); for (String referenceName : document.getReferenceNames()) { Reference reference = document.getReferenceByName(referenceName); if (reference.isPersistent()) { if (reference instanceof AssociationImpl) { AssociationImpl association = (AssociationImpl) reference; if (association.getType() == AssociationType.composition) { setTransient(BindUtil.get(bean, referenceName)); } } else if (reference instanceof Collection) { Collection collection = (Collection) reference; if (collection.getType() != CollectionType.aggregation) { // set each element of the collection transient setTransient(BindUtil.get(bean, referenceName)); } } } } } } // set the data group of a bean and all its children public static void setDataGroup(Object object, String bizDataGroupId) throws Exception { if (object instanceof List<?>) { List<?> list = (List<?>) object; for (Object element : list) { setDataGroup(element, bizDataGroupId); } } else if (object instanceof AbstractPersistentBean) { AbstractPersistentBean bean = (AbstractPersistentBean) object; bean.setBizDataGroupId(bizDataGroupId); // set the bizDatagroup of references if applicable Customer customer = AbstractPersistence.get().getUser().getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); for (String referenceName : document.getReferenceNames()) { Reference reference = document.getReferenceByName(referenceName); if (reference.isPersistent()) { if (reference instanceof AssociationImpl) { AssociationImpl association = (AssociationImpl) reference; if (association.getType() == AssociationType.composition) { setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId); } } else if (reference instanceof Collection) { Collection collection = (Collection) reference; if (collection.getType() != CollectionType.aggregation) { // set each element of the collection transient setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId); } } } } } } public static String processStringValue(String value) { String result = value; if (result != null) { result = result.trim(); if (result.isEmpty()) { result = null; } } return result; } /** * Make an instance of a document bean with random values for its properties. * * @param <T> The type of Document bean to produce. * @param user * @param module * @param document The document (corresponds to type T) * @param depth How far to traverse the object graph - through associations and collections. * There are relationships that are never ending - ie Contact has Interactions which has User which has COntact * @return The randomly constructed bean. * @throws Exception */ public static <T extends Bean> T constructRandomInstance(User user, Module module, Document document, int depth) throws Exception { return UtilImpl.constructRandomInstance(user, module, document, 1, depth); } @SuppressWarnings("incomplete-switch") // content type missing from switch statement private static <T extends Bean> T constructRandomInstance(User user, Module module, Document document, int currentDepth, int maxDepth) throws Exception { T result = document.newInstance(user); for (Attribute attribute : document.getAllAttributes()) { String name = attribute.getName(); AttributeType type = attribute.getAttributeType(); switch (type) { case association: if (currentDepth < maxDepth) { AssociationImpl association = (AssociationImpl) attribute; Module associationModule = module; String associationModuleRef = module.getDocumentRefs().get(association.getDocumentName()).getReferencedModuleName(); if (associationModuleRef != null) { associationModule = user.getCustomer().getModule(associationModuleRef); } Document associationDocument = associationModule.getDocument(user.getCustomer(), association.getDocumentName()); BindUtil.set(result, name, UtilImpl.constructRandomInstance(user, associationModule, associationDocument, currentDepth + 1, maxDepth)); } break; case bool: BindUtil.set(result, name, Boolean.FALSE); break; case collection: if (currentDepth < maxDepth) { Collection collection = (Collection) attribute; Module collectionModule = module; String collectionModuleRef = module.getDocumentRefs().get(collection.getDocumentName()).getReferencedModuleName(); if (collectionModuleRef != null) { collectionModule = user.getCustomer().getModule(collectionModuleRef); } Document collectionDocument = collectionModule.getDocument(user.getCustomer(), collection.getDocumentName()); @SuppressWarnings("unchecked") List<Bean> list = (List<Bean>) BindUtil.get(result, name); list.add(UtilImpl.constructRandomInstance(user, collectionModule, collectionDocument, currentDepth + 1, maxDepth)); list.add(UtilImpl.constructRandomInstance(user, collectionModule, collectionDocument, currentDepth + 1, maxDepth)); } break; case colour: BindUtil.set(result, name, "#FFFFFF"); break; case date: case dateTime: case time: case timestamp: BindUtil.convertAndSet(result, name, new Date()); break; case decimal10: case decimal2: case decimal5: case integer: case longInteger: BindUtil.convertAndSet(result, name, new Integer((int) Math.random() * 10000)); break; case enumeration: // TODO work out how to set an enum value here break; case geometry: BindUtil.set(result, name, new GeometryFactory().createPoint(new Coordinate(0, 0))); break; case id: BindUtil.set(result, name, UUID.randomUUID().toString()); break; case markup: case memo: BindUtil.set(result, name, randomString(((int) (Math.random() * 255)) + 1)); break; case text: BindUtil.set(result, name, randomString(((LengthField) attribute).getLength())); } } return result; } private static String randomString(int length) { char[] guts = new char[length]; for (int i = 0; i < length; i++) { guts[i] = Character.toChars(65 + (int) (Math.random() * 26))[0]; } return String.valueOf(guts); } }
skyve-core/src/org/skyve/impl/util/UtilImpl.java
package org.skyve.impl.util; import java.io.Serializable; import java.net.URL; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Logger; import org.hibernate.proxy.HibernateProxy; import org.hibernate.util.SerializationHelper; import org.skyve.CORE; import org.skyve.domain.Bean; import org.skyve.domain.messages.DomainException; import org.skyve.impl.bind.BindUtil; import org.skyve.impl.domain.AbstractPersistentBean; import org.skyve.impl.metadata.model.document.AssociationImpl; import org.skyve.impl.metadata.model.document.field.LengthField; import org.skyve.impl.persistence.AbstractPersistence; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.metadata.model.document.Association.AssociationType; import org.skyve.metadata.model.document.Collection; import org.skyve.metadata.model.document.Collection.CollectionType; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Reference; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.User; import org.skyve.util.BeanVisitor; import org.skyve.impl.util.UtilImpl; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; public class UtilImpl { /** * Disallow instantiation */ private UtilImpl() { // no-op } public static boolean XML_TRACE = true; public static boolean HTTP_TRACE = false; public static boolean QUERY_TRACE = false; public static boolean COMMAND_TRACE = false; public static boolean FACES_TRACE = false; public static boolean SQL_TRACE = false; public static boolean CONTENT_TRACE = false; public static boolean SECURITY_TRACE = false; public static boolean BIZLET_TRACE = false; public static boolean DIRTY_TRACE = false; public static boolean PRETTY_SQL_OUTPUT = false; public static final Logger LOGGER = Logger.getLogger("SKYVE"); // This is set in the web.xml but defaults to windows // as a dev environment for design time and generation gear public static String CONTENT_DIRECTORY = "/_/Apps/content/"; // The cron expression to use to fire off the content garbage collection // Defaults to run at 7 past the hour every hour. public static String CONTENT_GC_CRON = "0 7 0/1 1/1 * ? *"; // Should the attachments be stored on the file system or inline. public static boolean CONTENT_FILE_STORAGE = true; // This is set in web.xml and should only be used when the APP server in use // doesn't allow us to get the absolute path of a resource - jboss 4.0.5.GA, WebLogic or any zipped deployment public static String APPS_JAR_DIRECTORY; public static boolean DEV_MODE = false; // If it is null, then the login infrastructure will prompt for the customer name. // If it is set, the customer will be set to that value always. // This property is also used for single sign on purposes. public static String CUSTOMER = null; // eg https://www.bizhub.com.au public static String SERVER_URL = null; // eg /bizhub/web public static String SKYVE_CONTEXT = null; // eg /init.biz public static String HOME_URI = null; // This is the path on the server file system of the web context root public static String SKYVE_CONTEXT_REAL_PATH = null; // Implementations of Key SKYVE classes public static String SKYVE_REPOSITORY_CLASS = null; public static String SKYVE_PERSISTENCE_CLASS = null; public static String SKYVE_CONTENT_MANAGER_CLASS = null; // The directory used for temp files for file uploads etc public static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir"); public static boolean USING_JPA = false; // For conversations cache public static int MAX_CONVERSATIONS_IN_MEMORY = 1000; public static int CONVERSATION_EVICTION_TIME_MINUTES = 60; // For database public static String DATASOURCE = null; public static String STANDALONE_DATABASE_JDBC_DRIVER = null; public static String STANDALONE_DATABASE_CONNECTION_URL = null; public static String STANDALONE_DATABASE_USERNAME = null; public static String STANDALONE_DATABASE_PASSWORD = null; public static String DIALECT = "MySQL5InnoDBDialect"; public static boolean DDL_SYNC = true; // For E-Mail public static String SMTP = null; public static String SMTP_PORT = null; public static String SMTP_UID = null; public static String SMTP_PWD = null; public static String SMTP_SENDER = null; // used to intercept all email and send to this test email account public static String SMTP_TEST_RECIPIENT = null; // used to switch whether to send an email or not - false to actually send the email public static boolean SMTP_TEST_BOGUS_SEND = false; // Password hash algorithm public static String PASSWORD_HASHING_ALGORITHM = "MD5"; // For versioning javascript for web site public static final String JAVASCRIPT_FILE_VERSION = "20160426"; public static final String SKYVE_VERSION = "20160426"; public static final String SMART_CLIENT_DIR = "isomorphic110"; private static String absoluteBasePath; public static String getAbsoluteBasePath() { if (absoluteBasePath == null) { if (APPS_JAR_DIRECTORY != null) { absoluteBasePath = APPS_JAR_DIRECTORY; } else { URL url = Thread.currentThread().getContextClassLoader().getResource("schemas/common.xsd"); absoluteBasePath = url.getPath(); absoluteBasePath = absoluteBasePath.substring(0, absoluteBasePath.length() - 18); // remove schemas/common.xsd absoluteBasePath = absoluteBasePath.replace('\\', '/'); } } return absoluteBasePath; } @SuppressWarnings("unchecked") public static final <T extends Serializable> T cloneBySerialization(T object) { return (T) SerializationHelper.clone(object); // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // new ObjectOutputStream(baos).writeObject(object); // ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); // return (T) ois.readObject(); // } // catch (Exception e) { // throw new IllegalArgumentException(e); // } } public static final <T extends Serializable> T cloneToTransientBySerialization(T object) throws Exception { if (object instanceof List<?>) { for (Object element : (List<?>) object) { if (element instanceof AbstractPersistentBean) { populateFully((AbstractPersistentBean) object); } } } else if (object instanceof AbstractPersistentBean) { populateFully((AbstractPersistentBean) object); } T result = cloneBySerialization(object); setTransient(result); return result; } /** * Recurse the bean ensuring that everything is touched and loaded from the database. * * @param bean The bean to load. * @throws DomainException * @throws MetaDataException */ public static void populateFully(final Bean bean) throws DomainException, MetaDataException { User user = CORE.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); // Ensure that everything is loaded new BeanVisitor(false, true, false) { @Override protected boolean accept(String binding, Document documentAccepted, Document owningDocument, Relation owningRelation, Bean beanAccepted) throws DomainException, MetaDataException { // do nothing - just visiting loads the instance from the database try { if (beanAccepted != bean) { if (beanAccepted instanceof HibernateProxy) { BindUtil.set(bean, binding, ((HibernateProxy) beanAccepted).getHibernateLazyInitializer().getImplementation()); } } } catch (Exception e) { throw new DomainException(e); } return true; } }.visit(document, bean, customer); } /** * Recurse a bean to determine if anything has changed */ private static class ChangedBeanVisitor extends BeanVisitor { private boolean changed = false; private ChangedBeanVisitor() { // Don't check inverses as they aren't cascaded anyway super(false, false, false); } @Override protected boolean accept(String binding, Document documentAccepted, Document owningDocument, Relation owningRelation, Bean beanAccepted) throws DomainException, MetaDataException { if (beanAccepted.isChanged()) { changed = true; if (UtilImpl.DIRTY_TRACE) UtilImpl.LOGGER.info("UtilImpl.hasChanged(): Bean " + beanAccepted.toString() + " with binding " + binding + " is DIRTY"); return false; } return true; } boolean isChanged() { return changed; } } /** * Recurse the bean to determine if anything has changed. * * @param bean The bean to test. * @return if the bean, its collections or its aggregated beans have mutated or not * @throws DomainException * @throws MetaDataException */ public static boolean hasChanged(Bean bean) throws DomainException, MetaDataException { User user = CORE.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); @SuppressWarnings("synthetic-access") ChangedBeanVisitor cbv = new ChangedBeanVisitor(); cbv.visit(document, bean, customer); return cbv.isChanged(); } /** * Utility method that tries to properly initialise the persistence layer proxies used by lazy loading. * * @param <T> * @param possibleProxy The possible proxy * @return the resolved proxy or possibleProxy */ @SuppressWarnings("unchecked") public static <T> T deproxy(T possibleProxy) throws ClassCastException { if (possibleProxy instanceof HibernateProxy) { return (T) ((HibernateProxy) possibleProxy).getHibernateLazyInitializer().getImplementation(); } return possibleProxy; } public static void setTransient(Object object) throws Exception { if (object instanceof List<?>) { List<?> list = (List<?>) object; for (Object element : list) { setTransient(element); } } else if (object instanceof AbstractPersistentBean) { AbstractPersistentBean bean = (AbstractPersistentBean) object; bean.setBizId(UUID.randomUUID().toString()); bean.setBizLock(null); bean.setBizVersion(null); // set references transient if applicable Customer customer = AbstractPersistence.get().getUser().getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); for (String referenceName : document.getReferenceNames()) { Reference reference = document.getReferenceByName(referenceName); if (reference.isPersistent()) { if (reference instanceof AssociationImpl) { AssociationImpl association = (AssociationImpl) reference; if (association.getType() == AssociationType.composition) { setTransient(BindUtil.get(bean, referenceName)); } } else if (reference instanceof Collection) { Collection collection = (Collection) reference; if (collection.getType() != CollectionType.aggregation) { // set each element of the collection transient setTransient(BindUtil.get(bean, referenceName)); } } } } } } // set the data group of a bean and all its children public static void setDataGroup(Object object, String bizDataGroupId) throws Exception { if (object instanceof List<?>) { List<?> list = (List<?>) object; for (Object element : list) { setDataGroup(element, bizDataGroupId); } } else if (object instanceof AbstractPersistentBean) { AbstractPersistentBean bean = (AbstractPersistentBean) object; bean.setBizDataGroupId(bizDataGroupId); // set the bizDatagroup of references if applicable Customer customer = AbstractPersistence.get().getUser().getCustomer(); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); for (String referenceName : document.getReferenceNames()) { Reference reference = document.getReferenceByName(referenceName); if (reference.isPersistent()) { if (reference instanceof AssociationImpl) { AssociationImpl association = (AssociationImpl) reference; if (association.getType() == AssociationType.composition) { setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId); } } else if (reference instanceof Collection) { Collection collection = (Collection) reference; if (collection.getType() != CollectionType.aggregation) { // set each element of the collection transient setDataGroup(BindUtil.get(bean, referenceName), bizDataGroupId); } } } } } } public static String processStringValue(String value) { String result = value; if (result != null) { result = result.trim(); if (result.isEmpty()) { result = null; } } return result; } /** * Make an instance of a document bean with random values for its properties. * * @param <T> The type of Document bean to produce. * @param user * @param module * @param document The document (corresponds to type T) * @param depth How far to traverse the object graph - through associations and collections. * There are relationships that are never ending - ie Contact has Interactions which has User which has COntact * @return The randomly constructed bean. * @throws Exception */ public static <T extends Bean> T constructRandomInstance(User user, Module module, Document document, int depth) throws Exception { return UtilImpl.constructRandomInstance(user, module, document, 1, depth); } @SuppressWarnings("incomplete-switch") // content type missing from switch statement private static <T extends Bean> T constructRandomInstance(User user, Module module, Document document, int currentDepth, int maxDepth) throws Exception { T result = document.newInstance(user); for (Attribute attribute : document.getAllAttributes()) { String name = attribute.getName(); AttributeType type = attribute.getAttributeType(); switch (type) { case association: if (currentDepth < maxDepth) { AssociationImpl association = (AssociationImpl) attribute; Module associationModule = module; String associationModuleRef = module.getDocumentRefs().get(association.getDocumentName()).getReferencedModuleName(); if (associationModuleRef != null) { associationModule = user.getCustomer().getModule(associationModuleRef); } Document associationDocument = associationModule.getDocument(user.getCustomer(), association.getDocumentName()); BindUtil.set(result, name, UtilImpl.constructRandomInstance(user, associationModule, associationDocument, currentDepth + 1, maxDepth)); } break; case bool: BindUtil.set(result, name, Boolean.FALSE); break; case collection: if (currentDepth < maxDepth) { Collection collection = (Collection) attribute; Module collectionModule = module; String collectionModuleRef = module.getDocumentRefs().get(collection.getDocumentName()).getReferencedModuleName(); if (collectionModuleRef != null) { collectionModule = user.getCustomer().getModule(collectionModuleRef); } Document collectionDocument = collectionModule.getDocument(user.getCustomer(), collection.getDocumentName()); @SuppressWarnings("unchecked") List<Bean> list = (List<Bean>) BindUtil.get(result, name); list.add(UtilImpl.constructRandomInstance(user, collectionModule, collectionDocument, currentDepth + 1, maxDepth)); list.add(UtilImpl.constructRandomInstance(user, collectionModule, collectionDocument, currentDepth + 1, maxDepth)); } break; case colour: BindUtil.set(result, name, "#FFFFFF"); break; case date: case dateTime: case time: case timestamp: BindUtil.convertAndSet(result, name, new Date()); break; case decimal10: case decimal2: case decimal5: case integer: case longInteger: BindUtil.convertAndSet(result, name, new Integer((int) Math.random() * 10000)); break; case enumeration: // TODO work out how to set an enum value here break; case geometry: BindUtil.set(result, name, new GeometryFactory().createPoint(new Coordinate(0, 0))); break; case id: BindUtil.set(result, name, UUID.randomUUID().toString()); break; case markup: case memo: BindUtil.set(result, name, randomString(((int) (Math.random() * 255)) + 1)); break; case text: BindUtil.set(result, name, randomString(((LengthField) attribute).getLength())); } } return result; } private static String randomString(int length) { char[] guts = new char[length]; for (int i = 0; i < length; i++) { guts[i] = Character.toChars(65 + (int) (Math.random() * 26))[0]; } return String.valueOf(guts); } }
Skyve 20160505.
skyve-core/src/org/skyve/impl/util/UtilImpl.java
Skyve 20160505.
<ide><path>kyve-core/src/org/skyve/impl/util/UtilImpl.java <ide> public static String PASSWORD_HASHING_ALGORITHM = "MD5"; <ide> <ide> // For versioning javascript for web site <del> public static final String JAVASCRIPT_FILE_VERSION = "20160426"; <del> public static final String SKYVE_VERSION = "20160426"; <add> public static final String JAVASCRIPT_FILE_VERSION = "20160505"; <add> public static final String SKYVE_VERSION = "20160505"; <ide> public static final String SMART_CLIENT_DIR = "isomorphic110"; <ide> <ide> private static String absoluteBasePath;
JavaScript
agpl-3.0
d75ffa51eab1e14d339bfee91a328c4616644012
0
MelvinTo/firewalla,firewalla/firewalla,firewalla/firewalla,MelvinTo/firewalla,firewalla/firewalla,MelvinTo/firewalla,MelvinTo/firewalla,firewalla/firewalla,firewalla/firewalla,MelvinTo/firewalla
/* Copyright 2016 Firewalla LLC * * 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. * * 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/>. */ 'use strict'; const log = require('../net2/logger.js')(__filename); const Sensor = require('./Sensor.js').Sensor; const extensionManager = require('./ExtensionManager.js') const sem = require('../sensor/SensorEventManager.js').getInstance(); const f = require('../net2/Firewalla.js'); const userConfigFolder = f.getUserConfigFolder(); const dnsmasqConfigFolder = `${userConfigFolder}/dnsmasq`; const FAMILY_DNS = ["8.8.8.8"]; // these are just backup servers const fs = require('fs'); const Promise = require('bluebird'); Promise.promisifyAll(fs); const DNSMASQ = require('../extension/dnsmasq/dnsmasq.js'); const dnsmasq = new DNSMASQ(); const exec = require('child-process-promise').exec; const fc = require('../net2/config.js'); const spt = require('../net2/SystemPolicyTool')(); const rclient = require('../util/redis_manager.js').getRedisClient(); const updateFeature = "family"; const updateFlag = "2"; class FamilyProtectPlugin extends Sensor { async run() { this.systemSwitch = false; this.adminSystemSwitch = false; this.enabledMacAddresses = {}; extensionManager.registerExtension("family", this, { applyPolicy: this.applyPolicy, start: this.start, stop: this.stop }); if (await rclient.hgetAsync("sys:upgrade", updateFeature) != updateFlag) { const isPolicyEnabled = await spt.isPolicyEnabled('family'); if (isPolicyEnabled) { await fc.enableDynamicFeature("family"); } await rclient.hsetAsync("sys:upgrade", updateFeature, updateFlag) } await exec(`mkdir -p ${dnsmasqConfigFolder}`); sem.once('IPTABLES_READY', async () => { if (fc.isFeatureOn("family_protect")) { await this.globalOn(); } else { await this.globalOff(); } fc.onFeature("family_protect", async (feature, status) => { if (feature !== "family_protect") { return; } if (status) { await this.globalOn(); } else { await this.globalOff(); } }) await this.job(); this.timer = setInterval(async () => { return this.job(); }, this.config.refreshInterval || 3600 * 1000); // one hour by default }) } async job() { await this.applyFamilyProtect(); } async apiRun() { } async applyPolicy(host, ip, policy) { log.info("Applying family protect policy:", ip, policy); try { if (ip === '0.0.0.0') { if (policy == true) { this.systemSwitch = true; if (fc.isFeatureOn("family_protect", true)) {//compatibility: new firewlla, old app await fc.enableDynamicFeature("family_protect"); } } else { this.systemSwitch = false; } return this.applySystemFamilyProtect(); } else { const macAddress = host && host.o && host.o.mac; if (macAddress) { if (policy == true) { this.enabledMacAddresses[macAddress] = 1; } else { delete this.enabledMacAddresses[macAddress]; } return this.applyDeviceFamilyProtect(macAddress); } } } catch (err) { log.error("Got error when applying family protect policy", err); } } async applyFamilyProtect() { await this.applySystemFamilyProtect(); for (const macAddress in this.enabledMacAddresses) { await this.applyDeviceFamilyProtect(macAddress); } } async applySystemFamilyProtect() { this.familyDnsAddr((err, dnsaddrs) => { if (this.systemSwitch && this.adminSystemSwitch) { return this.systemStart(dnsaddrs); } else { return this.systemStop(dnsaddrs); } }); } async applyDeviceFamilyProtect(macAddress) { this.familyDnsAddr((err, dnsaddrs) => { try { if (this.enabledMacAddresses[macAddress] && this.adminSystemSwitch) { return this.perDeviceStart(macAddress, dnsaddrs) } else { return this.perDeviceStop(macAddress, dnsaddrs); } } catch (err) { log.error(`Failed to apply family protect on device ${macAddress}, err: ${err}`); } }); } async systemStart(dnsaddrs) { dnsmasq.setDefaultNameServers("family", dnsaddrs); await dnsmasq.updateResolvConf(); await dnsmasq.restartDnsmasq(); } async systemStop() { dnsmasq.unsetDefaultNameServers("family"); // reset dns name servers to null no matter whether iptables dns change is failed or successful await dnsmasq.updateResolvConf(); await dnsmasq.restartDnsmasq(); } async perDeviceStart(macAddress, dnsaddrs) { const configFile = `${dnsmasqConfigFolder}/familyProtect_${macAddress}.conf`; const dnsmasqentry = `server=${dnsaddrs[0]}%${macAddress.toUpperCase()}\n`; await fs.writeFileAsync(configFile, dnsmasqentry); dnsmasq.restartDnsmasq(); } async perDeviceStop(macAddress) { const configFile = `${dnsmasqConfigFolder}/familyProtect_${macAddress}.conf`; try { await fs.unlinkAsync(configFile); } catch (err) { if (err.code === 'ENOENT') { log.info(`Dnsmasq: No ${configFile}, skip remove`); } else { log.warn(`Dnsmasq: Error when remove ${configFile}`, err); } } dnsmasq.restartDnsmasq(); } // global on/off async globalOn() { this.adminSystemSwitch = true; await this.applyFamilyProtect(); } async globalOff() { this.adminSystemSwitch = false; await this.applyFamilyProtect(); } familyDnsAddr(callback) { f.getBoneInfo((err, data) => { if (data && data.config && data.config.dns && data.config.dns.familymode) { callback(null, data.config.dns.familymode); } else { callback(null, FAMILY_DNS); } }); } } module.exports = FamilyProtectPlugin
sensor/FamilyProtectPlugin.js
/* Copyright 2016 Firewalla LLC * * 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. * * 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/>. */ 'use strict'; const log = require('../net2/logger.js')(__filename); const Sensor = require('./Sensor.js').Sensor; const extensionManager = require('./ExtensionManager.js') const sem = require('../sensor/SensorEventManager.js').getInstance(); const f = require('../net2/Firewalla.js'); const userConfigFolder = f.getUserConfigFolder(); const dnsmasqConfigFolder = `${userConfigFolder}/dnsmasq`; const FAMILY_DNS = ["8.8.8.8"]; // these are just backup servers const fs = require('fs'); const Promise = require('bluebird'); Promise.promisifyAll(fs); const DNSMASQ = require('../extension/dnsmasq/dnsmasq.js'); const dnsmasq = new DNSMASQ(); const exec = require('child-process-promise').exec; const fc = require('../net2/config.js'); const spt = require('../net2/SystemPolicyTool')(); const rclient = require('../util/redis_manager.js').getRedisClient(); const updateFeature = "family"; const updateFlag = "2"; class FamilyProtectPlugin extends Sensor { async run() { this.systemSwitch = false; this.adminSystemSwitch = false; this.enabledMacAddresses = {}; extensionManager.registerExtension("family", this, { applyPolicy: this.applyPolicy, start: this.start, stop: this.stop }); if (await rclient.hgetAsync("sys:upgrade", updateFeature) != updateFlag) { const isPolicyEnabled = await spt.isPolicyEnabled('family'); if (isPolicyEnabled) { await fc.enableDynamicFeature("family"); } await rclient.hsetAsync("sys:upgrade", updateFeature, updateFlag) } await exec(`mkdir -p ${dnsmasqConfigFolder}`); sem.once('IPTABLES_READY', async () => { if (fc.isFeatureOn("family_protect")) { await this.globalOn(); } else { await this.globalOff(); } fc.onFeature("family_protect", async (feature, status) => { if (feature !== "family_protect") { return; } if (status) { await this.globalOn(); } else { await this.globalOff(); } }) await this.job(); this.timer = setInterval(async () => { return this.job(); }, this.config.refreshInterval || 3600 * 1000); // one hour by default }) } async job() { await this.applyFamilyProtect(); } async apiRun() { } async applyPolicy(host, ip, policy) { log.info("Applying family protect policy:", ip, policy); try { if (ip === '0.0.0.0') { if (policy == true) { this.systemSwitch = true; if (fc.isFeatureOn("family_protect", true)) {//compatibility: new firewlla, old app await fc.enableDynamicFeature("family_protect"); } } else { this.systemSwitch = false; } return this.applySystemFamilyProtect(); } else { const macAddress = host && host.o && host.o.mac; if (macAddress) { if (policy == true) { this.enabledMacAddresses[macAddress] = 1; } else { delete this.enabledMacAddresses[macAddress]; } return this.applyDeviceFamilyProtect(macAddress); } } } catch (err) { log.error("Got error when applying family protect policy", err); } } async applyFamilyProtect() { await this.applySystemFamilyProtect(); for (const macAddress in this.enabledMacAddresses) { await this.applyDeviceFamilyProtect(macAddress); } } async applySystemFamilyProtect() { this.familyDnsAddr((err, dnsaddrs) => { if (this.systemSwitch && this.adminSystemSwitch) { return this.systemStart(dnsaddrs); } else { return this.systemStop(dnsaddrs); } }); } async applyDeviceFamilyProtect(macAddress) { this.familyDnsAddr((err, dnsaddrs) => { try { if (this.enabledMacAddresses[macAddress] && this.adminSystemSwitch) { return this.perDeviceStart(macAddress, dnsaddrs) } else { return this.perDeviceStop(macAddress, dnsaddrs); } } catch (err) { log.error(`Failed to apply family protect on device ${macAddress}, err: ${err}`); } }); } async systemStart(dnsaddrs) { dnsmasq.setDefaultNameServers("family", dnsaddrs); dnsmasq.updateResolvConf(); } async systemStop() { dnsmasq.unsetDefaultNameServers("family"); // reset dns name servers to null no matter whether iptables dns change is failed or successful dnsmasq.updateResolvConf(); } async perDeviceStart(macAddress, dnsaddrs) { const configFile = `${dnsmasqConfigFolder}/familyProtect_${macAddress}.conf`; const dnsmasqentry = `server=${dnsaddrs[0]}%${macAddress.toUpperCase()}\n`; await fs.writeFileAsync(configFile, dnsmasqentry); dnsmasq.restartDnsmasq(); } async perDeviceStop(macAddress) { const configFile = `${dnsmasqConfigFolder}/familyProtect_${macAddress}.conf`; try { await fs.unlinkAsync(configFile); } catch (err) { if (err.code === 'ENOENT') { log.info(`Dnsmasq: No ${configFile}, skip remove`); } else { log.warn(`Dnsmasq: Error when remove ${configFile}`, err); } } dnsmasq.restartDnsmasq(); } // global on/off async globalOn() { this.adminSystemSwitch = true; await this.applyFamilyProtect(); } async globalOff() { this.adminSystemSwitch = false; await this.applyFamilyProtect(); } familyDnsAddr(callback) { f.getBoneInfo((err, data) => { if (data && data.config && data.config.dns && data.config.dns.familymode) { callback(null, data.config.dns.familymode); } else { callback(null, FAMILY_DNS); } }); } } module.exports = FamilyProtectPlugin
restart dnsmasq after system switch is changed
sensor/FamilyProtectPlugin.js
restart dnsmasq after system switch is changed
<ide><path>ensor/FamilyProtectPlugin.js <ide> <ide> async systemStart(dnsaddrs) { <ide> dnsmasq.setDefaultNameServers("family", dnsaddrs); <del> dnsmasq.updateResolvConf(); <add> await dnsmasq.updateResolvConf(); <add> await dnsmasq.restartDnsmasq(); <ide> } <ide> <ide> async systemStop() { <ide> dnsmasq.unsetDefaultNameServers("family"); // reset dns name servers to null no matter whether iptables dns change is failed or successful <del> dnsmasq.updateResolvConf(); <add> await dnsmasq.updateResolvConf(); <add> await dnsmasq.restartDnsmasq(); <ide> } <ide> <ide> async perDeviceStart(macAddress, dnsaddrs) {
Java
mit
e0c11616f56d732a61e38dd88a234851a00c6bae
0
churichard/friendcast,churichard/friendcast,churichard/friendcast
package hackru2014f.friendcast; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.widget.LoginButton; import java.util.Arrays; public class MainFragment extends Fragment { private static final String TAG = "MainFragment"; private UiLifecycleHelper uiHelper; private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(getActivity(), callback); uiHelper.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); // For scenarios where the main activity is launched and user // session is not null, the session state change notification // may not be triggered. Trigger it if it's open/closed. Session session = Session.getActiveSession(); if (session != null && (session.isOpened() || session.isClosed()) ) { onSessionStateChange(session, session.getState(), null); } uiHelper.onResume(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_main, container, false); LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton); authButton.setFragment(this); authButton.setReadPermissions(Arrays.asList("public_profile", "user_friends")); return view; } private void onSessionStateChange(Session session, SessionState state, Exception exception) { if (state.isOpened()) { Log.i(TAG, "Logged in..."); } else if (state.isClosed()) { Log.i(TAG, "Logged out..."); } } }
app/src/main/java/hackru2014f/friendcast/MainFragment.java
package hackru2014f.friendcast; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.widget.LoginButton; public class MainFragment extends Fragment { private static final String TAG = "MainFragment"; private UiLifecycleHelper uiHelper; private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(getActivity(), callback); uiHelper.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); // For scenarios where the main activity is launched and user // session is not null, the session state change notification // may not be triggered. Trigger it if it's open/closed. Session session = Session.getActiveSession(); if (session != null && (session.isOpened() || session.isClosed()) ) { onSessionStateChange(session, session.getState(), null); } uiHelper.onResume(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_main, container, false); LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton); authButton.setFragment(this); return view; } private void onSessionStateChange(Session session, SessionState state, Exception exception) { if (state.isOpened()) { Log.i(TAG, "Logged in..."); } else if (state.isClosed()) { Log.i(TAG, "Logged out..."); } } }
Added extra permissions
app/src/main/java/hackru2014f/friendcast/MainFragment.java
Added extra permissions
<ide><path>pp/src/main/java/hackru2014f/friendcast/MainFragment.java <ide> import com.facebook.SessionState; <ide> import com.facebook.UiLifecycleHelper; <ide> import com.facebook.widget.LoginButton; <add> <add>import java.util.Arrays; <ide> <ide> public class MainFragment extends Fragment { <ide> private static final String TAG = "MainFragment"; <ide> <ide> LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton); <ide> authButton.setFragment(this); <add> authButton.setReadPermissions(Arrays.asList("public_profile", "user_friends")); <ide> <ide> return view; <ide> }
Java
apache-2.0
839c766d9a8a563b645810d8485abea000f781f6
0
rcordovano/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy
/* * Autopsy Forensic Browser * * Copyright 2011-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.textextractors; import com.google.common.collect.ImmutableList; import com.google.common.io.CharSource; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PushbackReader; import java.io.Reader; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FilenameUtils; import org.apache.tika.Tika; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.parser.ParsingReader; import org.apache.tika.parser.microsoft.OfficeParserConfig; import org.apache.tika.parser.ocr.TesseractOCRConfig; import org.apache.tika.parser.pdf.PDFParserConfig; import org.openide.util.NbBundle; import org.openide.modules.InstalledFileLocator; import org.openide.util.Lookup; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.coreutils.ExecUtil; import org.sleuthkit.autopsy.coreutils.ExecUtil.ProcessTerminator; import org.sleuthkit.autopsy.coreutils.PlatformUtil; import org.sleuthkit.autopsy.datamodel.ContentUtils; import org.sleuthkit.autopsy.textextractors.extractionconfigs.ImageFileExtractionConfig; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ReadContentInputStream; /** * Extracts text from Tika supported content. Protects against Tika parser hangs * (for unexpected/corrupt content) using a timeout mechanism. */ final class TikaTextExtractor extends TextExtractor { //Mimetype groups to aassist extractor implementations in ignoring binary and //archive files. private static final List<String> BINARY_MIME_TYPES = ImmutableList.of( //ignore binary blob data, for which string extraction will be used "application/octet-stream", //NON-NLS "application/x-msdownload"); //NON-NLS /** * generally text extractors should ignore archives and let unpacking * modules take care of them */ private static final List<String> ARCHIVE_MIME_TYPES = ImmutableList.of( //ignore unstructured binary and compressed data, for which string extraction or unzipper works better "application/x-7z-compressed", //NON-NLS "application/x-ace-compressed", //NON-NLS "application/x-alz-compressed", //NON-NLS "application/x-arj", //NON-NLS "application/vnd.ms-cab-compressed", //NON-NLS "application/x-cfs-compressed", //NON-NLS "application/x-dgc-compressed", //NON-NLS "application/x-apple-diskimage", //NON-NLS "application/x-gca-compressed", //NON-NLS "application/x-dar", //NON-NLS "application/x-lzx", //NON-NLS "application/x-lzh", //NON-NLS "application/x-rar-compressed", //NON-NLS "application/x-stuffit", //NON-NLS "application/x-stuffitx", //NON-NLS "application/x-gtar", //NON-NLS "application/x-archive", //NON-NLS "application/x-executable", //NON-NLS "application/x-gzip", //NON-NLS "application/zip", //NON-NLS "application/x-zoo", //NON-NLS "application/x-cpio", //NON-NLS "application/x-shar", //NON-NLS "application/x-tar", //NON-NLS "application/x-bzip", //NON-NLS "application/x-bzip2", //NON-NLS "application/x-lzip", //NON-NLS "application/x-lzma", //NON-NLS "application/x-lzop", //NON-NLS "application/x-z", //NON-NLS "application/x-compress"); //NON-NLS private static final java.util.logging.Logger tikaLogger = java.util.logging.Logger.getLogger("Tika"); //NON-NLS private final ExecutorService tikaParseExecutor = Executors.newSingleThreadExecutor(); private static final String SQLITE_MIMETYPE = "application/x-sqlite3"; private final AutoDetectParser parser = new AutoDetectParser(); private final Content content; private boolean tesseractOCREnabled; private static final String TESSERACT_DIR_NAME = "Tesseract-OCR"; //NON-NLS private static final String TESSERACT_EXECUTABLE = "tesseract.exe"; //NON-NLS private static final File TESSERACT_PATH = locateTesseractExecutable(); private static final String LANGUAGE_PACKS = getLanguagePacks(); private ProcessTerminator processTerminator; private static final List<String> TIKA_SUPPORTED_TYPES = new Tika().getParser().getSupportedTypes(new ParseContext()) .stream() .map(mt -> mt.getType() + "/" + mt.getSubtype()) .collect(Collectors.toList()); public TikaTextExtractor(Content content) { this.content = content; } /** * Returns a reader that will iterate over the text extracted from Apache * Tika. * * @param content Supported source content to extract * * @return Reader that contains Apache Tika extracted text * * @throws * org.sleuthkit.autopsy.textextractors.TextExtractor.TextExtractorException */ @Override public Reader getReader() throws ExtractionException { InputStream stream = new ReadContentInputStream(content); Metadata metadata = new Metadata(); ParseContext parseContext = new ParseContext(); parseContext.set(Parser.class, parser); // Use the more memory efficient Tika SAX parsers for DOCX and // PPTX files (it already uses SAX for XLSX). OfficeParserConfig officeParserConfig = new OfficeParserConfig(); officeParserConfig.setUseSAXPptxExtractor(true); officeParserConfig.setUseSAXDocxExtractor(true); parseContext.set(OfficeParserConfig.class, officeParserConfig); //If Tesseract has been and installed and is set to be used.... if (TESSERACT_PATH != null && tesseractOCREnabled && PlatformUtil.isWindowsOS() == true) { if (content instanceof AbstractFile) { AbstractFile file = ((AbstractFile) content); //Run OCR on images with Tesseract directly. //Reassign the stream we will send to Tika to point to the //output file produced by Tesseract. if (file.getMIMEType().toLowerCase().contains("image")) { stream = runOcrAndGetOutputStream(file); } else { //Otherwise, go through Tika for PDFs so that it can //extract images and run Tesseract on them. PDFParserConfig pdfConfig = new PDFParserConfig(); // Extracting the inline images and letting Tesseract run on each inline image. // https://wiki.apache.org/tika/PDFParser%20%28Apache%20PDFBox%29 // https://tika.apache.org/1.7/api/org/apache/tika/parser/pdf/PDFParserConfig.html pdfConfig.setExtractInlineImages(true); // Multiple pages within a PDF file might refer to the same underlying image. pdfConfig.setExtractUniqueInlineImagesOnly(true); parseContext.set(PDFParserConfig.class, pdfConfig); // Configure Tesseract parser to perform OCR TesseractOCRConfig ocrConfig = new TesseractOCRConfig(); String tesseractFolder = TESSERACT_PATH.getParent(); ocrConfig.setTesseractPath(tesseractFolder); // Tesseract expects language data packs to be in a subdirectory of tesseractFolder, in a folder called "tessdata". // If they are stored somewhere else, use ocrConfig.setTessdataPath(String tessdataPath) to point to them ocrConfig.setLanguage(LANGUAGE_PACKS); parseContext.set(TesseractOCRConfig.class, ocrConfig); } } } //Make the creation of a TikaReader a cancellable future in case it takes too long Future<Reader> future = tikaParseExecutor.submit(new GetTikaReader(parser, stream, metadata, parseContext)); try { final Reader tikaReader = future.get(getTimeout(content.getSize()), TimeUnit.SECONDS); //check if the reader is empty PushbackReader pushbackReader = new PushbackReader(tikaReader); int read = pushbackReader.read(); if (read == -1) { throw new ExtractionException("Unable to extract text: Tika returned empty reader for " + content); } pushbackReader.unread(read); //concatenate parsed content and meta data into a single reader. CharSource metaDataCharSource = getMetaDataCharSource(metadata); return CharSource.concat(new ReaderCharSource(pushbackReader), metaDataCharSource).openStream(); } catch (TimeoutException te) { final String msg = NbBundle.getMessage(this.getClass(), "AbstractFileTikaTextExtract.index.tikaParseTimeout.text", content.getId(), content.getName()); throw new ExtractionException(msg, te); } catch (ExtractionException ex) { throw ex; } catch (Exception ex) { tikaLogger.log(Level.WARNING, "Exception: Unable to Tika parse the content" + content.getId() + ": " + content.getName(), ex.getCause()); //NON-NLS final String msg = NbBundle.getMessage(this.getClass(), "AbstractFileTikaTextExtract.index.exception.tikaParse.msg", content.getId(), content.getName()); throw new ExtractionException(msg, ex); } finally { future.cancel(true); } } /** * Run OCR and return the file stream produced by Tesseract. * * @param file Image file to run OCR on * * @return InputStream connected to the output file that Tesseract produced. * * @throws * org.sleuthkit.autopsy.textextractors.TextExtractor.ExtractionException */ private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { File inputFile = null; File outputFile = null; try { //Write file to temp directory String localDiskPath = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + file.getId() + file.getName(); inputFile = new File(localDiskPath); ContentUtils.writeToFile(content, inputFile); //Build tesseract commands ProcessBuilder process = new ProcessBuilder(); String outputFilePath = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + file.getId() + "output"; String executeablePath = TESSERACT_PATH.toString(); process.command(executeablePath, //Source image path String.format("\"%s\"", inputFile.getAbsolutePath()), //Output path String.format("\"%s\"", outputFilePath), //language pack command flag "-l", LANGUAGE_PACKS); //If the ProcessTerminator was supplied during //configuration apply it here. if (processTerminator != null) { ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); } else { ExecUtil.execute(process); } //Open an input stream on the output file to send to tika. //Tesseract spits out a .txt file outputFile = new File(outputFilePath + ".txt"); //When CleanUpStream is closed, it automatically //deletes the outputFile in the temp directory. return new CleanUpStream(outputFile); } catch (NoCurrentCaseException | IOException ex) { if (outputFile != null) { outputFile.delete(); } throw new ExtractionException("Could not successfully run Tesseract", ex); } finally { if (inputFile != null) { inputFile.delete(); } } } /** * Wraps the creation of a TikaReader into a Future so that it can be * cancelled. */ private class GetTikaReader implements Callable<Reader> { private final AutoDetectParser parser; private final InputStream stream; private final Metadata metadata; private final ParseContext parseContext; public GetTikaReader(AutoDetectParser parser, InputStream stream, Metadata metadata, ParseContext parseContext) { this.parser = parser; this.stream = stream; this.metadata = metadata; this.parseContext = parseContext; } @Override public Reader call() throws Exception { return new ParsingReader(parser, stream, metadata, parseContext); } } /** * Automatically deletes the underlying File when the close() method is * called. This is used to delete the Output file produced from Tesseract * once it has been read by Tika. */ private class CleanUpStream extends FileInputStream { private File file; public CleanUpStream(File file) throws FileNotFoundException { super(file); this.file = file; } @Override public void close() throws IOException { try { super.close(); } finally { if (file != null) { file.delete(); file = null; } } } } /** * Finds and returns the path to the Tesseract executable, if able. * * @return A File reference or null. */ private static File locateTesseractExecutable() { if (!PlatformUtil.isWindowsOS()) { return null; } String executableToFindName = Paths.get(TESSERACT_DIR_NAME, TESSERACT_EXECUTABLE).toString(); File exeFile = InstalledFileLocator.getDefault().locate(executableToFindName, TikaTextExtractor.class.getPackage().getName(), false); if (null == exeFile) { return null; } if (!exeFile.canExecute()) { return null; } return exeFile; } /** * Gets a CharSource that wraps a formated representation of the given * Metadata. * * @param metadata The Metadata to wrap as a CharSource * * @return A CharSource for the given MetaData */ static private CharSource getMetaDataCharSource(Metadata metadata) { return CharSource.wrap( new StringBuilder("\n\n------------------------------METADATA------------------------------\n\n") .append(Stream.of(metadata.names()).sorted() .map(key -> key + ": " + metadata.get(key)) .collect(Collectors.joining("\n")) )); } /** * Determines if Tika is supported for this content type and mimetype. * * @param content Source content to read * @param detectedFormat Mimetype of content * * @return Flag indicating support for reading content type */ @Override public boolean isSupported(Content content, String detectedFormat) { if (detectedFormat == null || BINARY_MIME_TYPES.contains(detectedFormat) //any binary unstructured blobs (string extraction will be used) || ARCHIVE_MIME_TYPES.contains(detectedFormat) || (detectedFormat.startsWith("video/") && !detectedFormat.equals("video/x-flv")) //skip video other than flv (tika supports flv only) //NON-NLS || detectedFormat.equals(SQLITE_MIMETYPE) //Skip sqlite files, Tika cannot handle virtual tables and will fail with an exception. //NON-NLS ) { return false; } return TIKA_SUPPORTED_TYPES.contains(detectedFormat); } /** * Retrieves all of the installed language packs from their designated * directory location to be used to configure Tesseract OCR. * * @return String of all language packs available for Tesseract to use */ private static String getLanguagePacks() { File languagePackRootDir = new File(TESSERACT_PATH.getParent(), "tessdata"); //Acceptable extensions for Tesseract-OCR version 3.05 language packs. //All extensions other than traineddata are associated with cube files that //have been made obsolete since version 4.0. List<String> acceptableExtensions = Arrays.asList("traineddata", "params", "lm", "fold", "bigrams", "nn", "word-freq", "size", "user-patterns", "user-words"); //Pull out only unique languagePacks HashSet<String> languagePacks = new HashSet<>(); if (languagePackRootDir.exists()) { for (File languagePack : languagePackRootDir.listFiles()) { if (languagePack.isDirectory() || !acceptableExtensions.contains( FilenameUtils.getExtension(languagePack.getName()))) { continue; } String threeLetterPackageName = languagePack.getName().substring(0, 3); //Ignore the eng language pack if accidentally added languagePacks.add(threeLetterPackageName); } } return String.join("+", languagePacks); } /** * Return timeout that should be used to index the content. * * @param size size of the content * * @return time in seconds to use a timeout */ private static int getTimeout(long size) { if (size < 1024 * 1024L) //1MB { return 60; } else if (size < 10 * 1024 * 1024L) //10MB { return 1200; } else if (size < 100 * 1024 * 1024L) //100MB { return 3600; } else { return 3 * 3600; } } /** * Determines how the extraction process will proceed given the settings * stored in this context instance. * * See the ImageFileExtractionConfig class in the extractionconfigs package * for available settings. * * @param context Instance containing config classes */ @Override public void setExtractionSettings(Lookup context) { if (context != null) { ImageFileExtractionConfig configInstance = context.lookup(ImageFileExtractionConfig.class); if (configInstance != null && Objects.nonNull(configInstance.getOCREnabled())) { this.tesseractOCREnabled = configInstance.getOCREnabled(); } ProcessTerminator terminatorInstance = context.lookup(ProcessTerminator.class); if (terminatorInstance != null) { this.processTerminator = terminatorInstance; } } } /** * An implementation of CharSource that just wraps an existing reader and * returns it in openStream(). */ private static class ReaderCharSource extends CharSource { private final Reader reader; ReaderCharSource(Reader reader) { this.reader = reader; } @Override public Reader openStream() throws IOException { return reader; } } }
Core/src/org/sleuthkit/autopsy/textextractors/TikaTextExtractor.java
/* * Autopsy Forensic Browser * * Copyright 2011-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.textextractors; import com.google.common.collect.ImmutableList; import com.google.common.io.CharSource; import java.io.File; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FilenameUtils; import org.apache.tika.Tika; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.parser.ParsingReader; import org.apache.tika.parser.microsoft.OfficeParserConfig; import org.apache.tika.parser.ocr.TesseractOCRConfig; import org.apache.tika.parser.pdf.PDFParserConfig; import org.openide.util.NbBundle; import org.openide.modules.InstalledFileLocator; import org.openide.util.Lookup; import org.sleuthkit.autopsy.coreutils.PlatformUtil; import org.sleuthkit.autopsy.textextractors.extractionconfigs.ImageFileExtractionConfig; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ReadContentInputStream; /** * Extracts text from Tika supported content. Protects against Tika parser hangs * (for unexpected/corrupt content) using a timeout mechanism. */ final class TikaTextExtractor extends TextExtractor { //Mimetype groups to aassist extractor implementations in ignoring binary and //archive files. private static final List<String> BINARY_MIME_TYPES = ImmutableList.of( //ignore binary blob data, for which string extraction will be used "application/octet-stream", //NON-NLS "application/x-msdownload"); //NON-NLS /** * generally text extractors should ignore archives and let unpacking * modules take care of them */ private static final List<String> ARCHIVE_MIME_TYPES = ImmutableList.of( //ignore unstructured binary and compressed data, for which string extraction or unzipper works better "application/x-7z-compressed", //NON-NLS "application/x-ace-compressed", //NON-NLS "application/x-alz-compressed", //NON-NLS "application/x-arj", //NON-NLS "application/vnd.ms-cab-compressed", //NON-NLS "application/x-cfs-compressed", //NON-NLS "application/x-dgc-compressed", //NON-NLS "application/x-apple-diskimage", //NON-NLS "application/x-gca-compressed", //NON-NLS "application/x-dar", //NON-NLS "application/x-lzx", //NON-NLS "application/x-lzh", //NON-NLS "application/x-rar-compressed", //NON-NLS "application/x-stuffit", //NON-NLS "application/x-stuffitx", //NON-NLS "application/x-gtar", //NON-NLS "application/x-archive", //NON-NLS "application/x-executable", //NON-NLS "application/x-gzip", //NON-NLS "application/zip", //NON-NLS "application/x-zoo", //NON-NLS "application/x-cpio", //NON-NLS "application/x-shar", //NON-NLS "application/x-tar", //NON-NLS "application/x-bzip", //NON-NLS "application/x-bzip2", //NON-NLS "application/x-lzip", //NON-NLS "application/x-lzma", //NON-NLS "application/x-lzop", //NON-NLS "application/x-z", //NON-NLS "application/x-compress"); //NON-NLS private static final java.util.logging.Logger tikaLogger = java.util.logging.Logger.getLogger("Tika"); //NON-NLS private final ExecutorService tikaParseExecutor = Executors.newSingleThreadExecutor(); private static final String SQLITE_MIMETYPE = "application/x-sqlite3"; private final AutoDetectParser parser = new AutoDetectParser(); private final Content content; private boolean tesseractOCREnabled; private static final String TESSERACT_DIR_NAME = "Tesseract-OCR"; //NON-NLS private static final String TESSERACT_EXECUTABLE = "tesseract.exe"; //NON-NLS private static final File TESSERACT_PATH = locateTesseractExecutable(); private static final String LANGUAGE_PACKS = getLanguagePacks(); private static final List<String> TIKA_SUPPORTED_TYPES = new Tika().getParser().getSupportedTypes(new ParseContext()) .stream() .map(mt -> mt.getType() + "/" + mt.getSubtype()) .collect(Collectors.toList()); public TikaTextExtractor(Content content) { this.content = content; } /** * Returns a reader that will iterate over the text extracted from Apache * Tika. * * @param content Supported source content to extract * * @return Reader that contains Apache Tika extracted text * * @throws * org.sleuthkit.autopsy.textextractors.TextExtractor.TextExtractorException */ @Override public Reader getReader() throws ExtractionException { ReadContentInputStream stream = new ReadContentInputStream(content); Metadata metadata = new Metadata(); ParseContext parseContext = new ParseContext(); parseContext.set(Parser.class, parser); // Use the more memory efficient Tika SAX parsers for DOCX and // PPTX files (it already uses SAX for XLSX). OfficeParserConfig officeParserConfig = new OfficeParserConfig(); officeParserConfig.setUseSAXPptxExtractor(true); officeParserConfig.setUseSAXDocxExtractor(true); parseContext.set(OfficeParserConfig.class, officeParserConfig); // configure OCR if it is enabled in KWS settings and installed on the machine if (TESSERACT_PATH != null && tesseractOCREnabled && PlatformUtil.isWindowsOS() == true) { // configure PDFParser. PDFParserConfig pdfConfig = new PDFParserConfig(); // Extracting the inline images and letting Tesseract run on each inline image. // https://wiki.apache.org/tika/PDFParser%20%28Apache%20PDFBox%29 // https://tika.apache.org/1.7/api/org/apache/tika/parser/pdf/PDFParserConfig.html pdfConfig.setExtractInlineImages(true); // Multiple pages within a PDF file might refer to the same underlying image. pdfConfig.setExtractUniqueInlineImagesOnly(true); parseContext.set(PDFParserConfig.class, pdfConfig); // Configure Tesseract parser to perform OCR TesseractOCRConfig ocrConfig = new TesseractOCRConfig(); String tesseractFolder = TESSERACT_PATH.getParent(); ocrConfig.setTesseractPath(tesseractFolder); // Tesseract expects language data packs to be in a subdirectory of tesseractFolder, in a folder called "tessdata". // If they are stored somewhere else, use ocrConfig.setTessdataPath(String tessdataPath) to point to them ocrConfig.setLanguage(LANGUAGE_PACKS); parseContext.set(TesseractOCRConfig.class, ocrConfig); } //Parse the file in a task, a convenient way to have a timeout... final Future<Reader> future = tikaParseExecutor.submit(() -> new ParsingReader(parser, stream, metadata, parseContext)); try { final Reader tikaReader = future.get(getTimeout(content.getSize()), TimeUnit.SECONDS); //check if the reader is empty PushbackReader pushbackReader = new PushbackReader(tikaReader); int read = pushbackReader.read(); if (read == -1) { throw new ExtractionException("Unable to extract text: Tika returned empty reader for " + content); } pushbackReader.unread(read); //concatenate parsed content and meta data into a single reader. CharSource metaDataCharSource = getMetaDataCharSource(metadata); return CharSource.concat(new ReaderCharSource(pushbackReader), metaDataCharSource).openStream(); } catch (TimeoutException te) { final String msg = NbBundle.getMessage(this.getClass(), "AbstractFileTikaTextExtract.index.tikaParseTimeout.text", content.getId(), content.getName()); throw new ExtractionException(msg, te); } catch (ExtractionException ex) { throw ex; } catch (Exception ex) { tikaLogger.log(Level.WARNING, "Exception: Unable to Tika parse the content" + content.getId() + ": " + content.getName(), ex.getCause()); //NON-NLS final String msg = NbBundle.getMessage(this.getClass(), "AbstractFileTikaTextExtract.index.exception.tikaParse.msg", content.getId(), content.getName()); throw new ExtractionException(msg, ex); } finally { future.cancel(true); } } /** * Finds and returns the path to the Tesseract executable, if able. * * @return A File reference or null. */ private static File locateTesseractExecutable() { if (!PlatformUtil.isWindowsOS()) { return null; } String executableToFindName = Paths.get(TESSERACT_DIR_NAME, TESSERACT_EXECUTABLE).toString(); File exeFile = InstalledFileLocator.getDefault().locate(executableToFindName, TikaTextExtractor.class.getPackage().getName(), false); if (null == exeFile) { return null; } if (!exeFile.canExecute()) { return null; } return exeFile; } /** * Gets a CharSource that wraps a formated representation of the given * Metadata. * * @param metadata The Metadata to wrap as a CharSource * * @return A CharSource for the given MetaData */ static private CharSource getMetaDataCharSource(Metadata metadata) { return CharSource.wrap( new StringBuilder("\n\n------------------------------METADATA------------------------------\n\n") .append(Stream.of(metadata.names()).sorted() .map(key -> key + ": " + metadata.get(key)) .collect(Collectors.joining("\n")) )); } /** * Determines if Tika is supported for this content type and mimetype. * * @param content Source content to read * @param detectedFormat Mimetype of content * * @return Flag indicating support for reading content type */ @Override public boolean isSupported(Content content, String detectedFormat) { if (detectedFormat == null || BINARY_MIME_TYPES.contains(detectedFormat) //any binary unstructured blobs (string extraction will be used) || ARCHIVE_MIME_TYPES.contains(detectedFormat) || (detectedFormat.startsWith("video/") && !detectedFormat.equals("video/x-flv")) //skip video other than flv (tika supports flv only) //NON-NLS || detectedFormat.equals(SQLITE_MIMETYPE) //Skip sqlite files, Tika cannot handle virtual tables and will fail with an exception. //NON-NLS ) { return false; } return TIKA_SUPPORTED_TYPES.contains(detectedFormat); } /** * Retrieves all of the installed language packs from their designated * directory location to be used to configure Tesseract OCR. * * @return String of all language packs available for Tesseract to use */ private static String getLanguagePacks() { File languagePackRootDir = new File(TESSERACT_PATH.getParent(), "tessdata"); //Acceptable extensions for Tesseract-OCR version 3.05 language packs. //All extensions other than traineddata are associated with cube files that //have been made obsolete since version 4.0. List<String> acceptableExtensions = Arrays.asList("traineddata", "params", "lm", "fold", "bigrams", "nn", "word-freq", "size", "user-patterns", "user-words"); //Pull out only unique languagePacks HashSet<String> languagePacks = new HashSet<>(); if (languagePackRootDir.exists()) { for (File languagePack : languagePackRootDir.listFiles()) { if (languagePack.isDirectory() || !acceptableExtensions.contains( FilenameUtils.getExtension(languagePack.getName()))) { continue; } String threeLetterPackageName = languagePack.getName().substring(0, 3); //Ignore the eng language pack if accidentally added languagePacks.add(threeLetterPackageName); } } return String.join("+", languagePacks); } /** * Return timeout that should be used to index the content. * * @param size size of the content * * @return time in seconds to use a timeout */ private static int getTimeout(long size) { if (size < 1024 * 1024L) //1MB { return 60; } else if (size < 10 * 1024 * 1024L) //10MB { return 1200; } else if (size < 100 * 1024 * 1024L) //100MB { return 3600; } else { return 3 * 3600; } } /** * Determines how the extraction process will proceed given the settings * stored in this context instance. * * See the ImageFileExtractionConfig class in the extractionconfigs package * for available settings. * * @param context Instance containing config classes */ @Override public void setExtractionSettings(Lookup context) { if (context != null) { ImageFileExtractionConfig configInstance = context.lookup(ImageFileExtractionConfig.class); if (configInstance == null) { return; } if (Objects.nonNull(configInstance.getOCREnabled())) { this.tesseractOCREnabled = configInstance.getOCREnabled(); } } } /** * An implementation of CharSource that just wraps an existing reader and * returns it in openStream(). */ private static class ReaderCharSource extends CharSource { private final Reader reader; ReaderCharSource(Reader reader) { this.reader = reader; } @Override public Reader openStream() throws IOException { return reader; } } }
Pulled the Tesseract use out of Tika and allow for them to be cancelled
Core/src/org/sleuthkit/autopsy/textextractors/TikaTextExtractor.java
Pulled the Tesseract use out of Tika and allow for them to be cancelled
<ide><path>ore/src/org/sleuthkit/autopsy/textextractors/TikaTextExtractor.java <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.io.CharSource; <ide> import java.io.File; <add>import java.io.FileInputStream; <add>import java.io.FileNotFoundException; <ide> import java.io.IOException; <add>import java.io.InputStream; <ide> import java.io.PushbackReader; <ide> import java.io.Reader; <ide> import java.nio.file.Paths; <ide> import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Objects; <add>import java.util.concurrent.Callable; <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.Future; <ide> import org.openide.util.NbBundle; <ide> import org.openide.modules.InstalledFileLocator; <ide> import org.openide.util.Lookup; <add>import org.sleuthkit.autopsy.casemodule.Case; <add>import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; <add>import org.sleuthkit.autopsy.coreutils.ExecUtil; <add>import org.sleuthkit.autopsy.coreutils.ExecUtil.ProcessTerminator; <ide> import org.sleuthkit.autopsy.coreutils.PlatformUtil; <add>import org.sleuthkit.autopsy.datamodel.ContentUtils; <ide> import org.sleuthkit.autopsy.textextractors.extractionconfigs.ImageFileExtractionConfig; <add>import org.sleuthkit.datamodel.AbstractFile; <ide> import org.sleuthkit.datamodel.Content; <ide> import org.sleuthkit.datamodel.ReadContentInputStream; <ide> <ide> private static final String TESSERACT_EXECUTABLE = "tesseract.exe"; //NON-NLS <ide> private static final File TESSERACT_PATH = locateTesseractExecutable(); <ide> private static final String LANGUAGE_PACKS = getLanguagePacks(); <add> private ProcessTerminator processTerminator; <ide> <ide> private static final List<String> TIKA_SUPPORTED_TYPES <ide> = new Tika().getParser().getSupportedTypes(new ParseContext()) <ide> */ <ide> @Override <ide> public Reader getReader() throws ExtractionException { <del> ReadContentInputStream stream = new ReadContentInputStream(content); <add> InputStream stream = new ReadContentInputStream(content); <ide> <ide> Metadata metadata = new Metadata(); <ide> ParseContext parseContext = new ParseContext(); <ide> officeParserConfig.setUseSAXDocxExtractor(true); <ide> parseContext.set(OfficeParserConfig.class, officeParserConfig); <ide> <del> // configure OCR if it is enabled in KWS settings and installed on the machine <add> //If Tesseract has been and installed and is set to be used.... <ide> if (TESSERACT_PATH != null && tesseractOCREnabled && PlatformUtil.isWindowsOS() == true) { <del> <del> // configure PDFParser. <del> PDFParserConfig pdfConfig = new PDFParserConfig(); <del> <del> // Extracting the inline images and letting Tesseract run on each inline image. <del> // https://wiki.apache.org/tika/PDFParser%20%28Apache%20PDFBox%29 <del> // https://tika.apache.org/1.7/api/org/apache/tika/parser/pdf/PDFParserConfig.html <del> pdfConfig.setExtractInlineImages(true); <del> // Multiple pages within a PDF file might refer to the same underlying image. <del> pdfConfig.setExtractUniqueInlineImagesOnly(true); <del> parseContext.set(PDFParserConfig.class, pdfConfig); <del> <del> // Configure Tesseract parser to perform OCR <del> TesseractOCRConfig ocrConfig = new TesseractOCRConfig(); <del> String tesseractFolder = TESSERACT_PATH.getParent(); <del> ocrConfig.setTesseractPath(tesseractFolder); <del> // Tesseract expects language data packs to be in a subdirectory of tesseractFolder, in a folder called "tessdata". <del> // If they are stored somewhere else, use ocrConfig.setTessdataPath(String tessdataPath) to point to them <del> ocrConfig.setLanguage(LANGUAGE_PACKS); <del> parseContext.set(TesseractOCRConfig.class, ocrConfig); <del> } <del> <del> //Parse the file in a task, a convenient way to have a timeout... <del> final Future<Reader> future = tikaParseExecutor.submit(() -> new ParsingReader(parser, stream, metadata, parseContext)); <add> if (content instanceof AbstractFile) { <add> AbstractFile file = ((AbstractFile) content); <add> //Run OCR on images with Tesseract directly. <add> //Reassign the stream we will send to Tika to point to the <add> //output file produced by Tesseract. <add> if (file.getMIMEType().toLowerCase().contains("image")) { <add> stream = runOcrAndGetOutputStream(file); <add> } else { <add> //Otherwise, go through Tika for PDFs so that it can <add> //extract images and run Tesseract on them. <add> PDFParserConfig pdfConfig = new PDFParserConfig(); <add> <add> // Extracting the inline images and letting Tesseract run on each inline image. <add> // https://wiki.apache.org/tika/PDFParser%20%28Apache%20PDFBox%29 <add> // https://tika.apache.org/1.7/api/org/apache/tika/parser/pdf/PDFParserConfig.html <add> pdfConfig.setExtractInlineImages(true); <add> // Multiple pages within a PDF file might refer to the same underlying image. <add> pdfConfig.setExtractUniqueInlineImagesOnly(true); <add> parseContext.set(PDFParserConfig.class, pdfConfig); <add> <add> // Configure Tesseract parser to perform OCR <add> TesseractOCRConfig ocrConfig = new TesseractOCRConfig(); <add> String tesseractFolder = TESSERACT_PATH.getParent(); <add> ocrConfig.setTesseractPath(tesseractFolder); <add> // Tesseract expects language data packs to be in a subdirectory of tesseractFolder, in a folder called "tessdata". <add> // If they are stored somewhere else, use ocrConfig.setTessdataPath(String tessdataPath) to point to them <add> ocrConfig.setLanguage(LANGUAGE_PACKS); <add> parseContext.set(TesseractOCRConfig.class, ocrConfig); <add> } <add> } <add> } <add> <add> //Make the creation of a TikaReader a cancellable future in case it takes too long <add> Future<Reader> future = tikaParseExecutor.submit(new GetTikaReader(parser, stream, metadata, parseContext)); <ide> try { <ide> final Reader tikaReader = future.get(getTimeout(content.getSize()), TimeUnit.SECONDS); <del> <ide> //check if the reader is empty <ide> PushbackReader pushbackReader = new PushbackReader(tikaReader); <ide> int read = pushbackReader.read(); <ide> throw new ExtractionException(msg, ex); <ide> } finally { <ide> future.cancel(true); <add> } <add> } <add> <add> /** <add> * Run OCR and return the file stream produced by Tesseract. <add> * <add> * @param file Image file to run OCR on <add> * <add> * @return InputStream connected to the output file that Tesseract produced. <add> * <add> * @throws <add> * org.sleuthkit.autopsy.textextractors.TextExtractor.ExtractionException <add> */ <add> private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { <add> File inputFile = null; <add> File outputFile = null; <add> try { <add> //Write file to temp directory <add> String localDiskPath = Case.getCurrentCaseThrows().getTempDirectory() <add> + File.separator + file.getId() + file.getName(); <add> inputFile = new File(localDiskPath); <add> ContentUtils.writeToFile(content, inputFile); <add> <add> //Build tesseract commands <add> ProcessBuilder process = new ProcessBuilder(); <add> String outputFilePath = Case.getCurrentCaseThrows().getTempDirectory() <add> + File.separator + file.getId() + "output"; <add> <add> String executeablePath = TESSERACT_PATH.toString(); <add> process.command(executeablePath, <add> //Source image path <add> String.format("\"%s\"", inputFile.getAbsolutePath()), <add> //Output path <add> String.format("\"%s\"", outputFilePath), <add> //language pack command flag <add> "-l", <add> LANGUAGE_PACKS); <add> <add> //If the ProcessTerminator was supplied during <add> //configuration apply it here. <add> if (processTerminator != null) { <add> ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); <add> } else { <add> ExecUtil.execute(process); <add> } <add> <add> //Open an input stream on the output file to send to tika. <add> //Tesseract spits out a .txt file <add> outputFile = new File(outputFilePath + ".txt"); <add> //When CleanUpStream is closed, it automatically <add> //deletes the outputFile in the temp directory. <add> return new CleanUpStream(outputFile); <add> } catch (NoCurrentCaseException | IOException ex) { <add> if (outputFile != null) { <add> outputFile.delete(); <add> } <add> throw new ExtractionException("Could not successfully run Tesseract", ex); <add> } finally { <add> if (inputFile != null) { <add> inputFile.delete(); <add> } <add> } <add> } <add> <add> /** <add> * Wraps the creation of a TikaReader into a Future so that it can be <add> * cancelled. <add> */ <add> private class GetTikaReader implements Callable<Reader> { <add> <add> private final AutoDetectParser parser; <add> private final InputStream stream; <add> private final Metadata metadata; <add> private final ParseContext parseContext; <add> <add> public GetTikaReader(AutoDetectParser parser, InputStream stream, <add> Metadata metadata, ParseContext parseContext) { <add> this.parser = parser; <add> this.stream = stream; <add> this.metadata = metadata; <add> this.parseContext = parseContext; <add> } <add> <add> @Override <add> public Reader call() throws Exception { <add> return new ParsingReader(parser, stream, metadata, parseContext); <add> } <add> } <add> <add> /** <add> * Automatically deletes the underlying File when the close() method is <add> * called. This is used to delete the Output file produced from Tesseract <add> * once it has been read by Tika. <add> */ <add> private class CleanUpStream extends FileInputStream { <add> <add> private File file; <add> <add> public CleanUpStream(File file) throws FileNotFoundException { <add> super(file); <add> this.file = file; <add> } <add> <add> @Override <add> public void close() throws IOException { <add> try { <add> super.close(); <add> } finally { <add> if (file != null) { <add> file.delete(); <add> file = null; <add> } <add> } <ide> } <ide> } <ide> <ide> public void setExtractionSettings(Lookup context) { <ide> if (context != null) { <ide> ImageFileExtractionConfig configInstance = context.lookup(ImageFileExtractionConfig.class); <del> if (configInstance == null) { <del> return; <del> } <del> if (Objects.nonNull(configInstance.getOCREnabled())) { <add> <add> if (configInstance != null && Objects.nonNull(configInstance.getOCREnabled())) { <ide> this.tesseractOCREnabled = configInstance.getOCREnabled(); <add> } <add> <add> ProcessTerminator terminatorInstance = context.lookup(ProcessTerminator.class); <add> if (terminatorInstance != null) { <add> this.processTerminator = terminatorInstance; <ide> } <ide> } <ide> }
JavaScript
agpl-3.0
e4cb049cf522b0e8d86b228354999480d8cf2f70
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
8ffc108a-2e64-11e5-9284-b827eb9e62be
helloWorld.js
8ff69f6a-2e64-11e5-9284-b827eb9e62be
8ffc108a-2e64-11e5-9284-b827eb9e62be
helloWorld.js
8ffc108a-2e64-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>8ff69f6a-2e64-11e5-9284-b827eb9e62be <add>8ffc108a-2e64-11e5-9284-b827eb9e62be
Java
apache-2.0
8d419ee769d3a9f275acc1fa8da56db5a902adab
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server; import com.google.common.annotations.VisibleForTesting; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import java.util.Optional; import java.util.function.Supplier; import static com.google.common.base.Strings.emptyToNull; import static io.spine.server.DeploymentType.APPENGINE_CLOUD; import static io.spine.server.DeploymentType.APPENGINE_EMULATOR; import static io.spine.server.DeploymentType.STANDALONE; import static java.util.Optional.ofNullable; /** * The default implementation of {@linkplain DeploymentType deployment type} * {@linkplain Supplier supplier}. */ class DeploymentDetector implements Supplier<DeploymentType> { @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_PATH = "com.google.appengine.runtime.environment"; @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE = "Production"; @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE = "Development"; private @MonotonicNonNull DeploymentType deploymentType; /** Prevent instantiation from outside. */ private DeploymentDetector() { } public static Supplier<DeploymentType> newInstance() { return new DeploymentDetector(); } @Override public DeploymentType get() { if (deploymentType == null) { deploymentType = detect(); } return deploymentType; } private static DeploymentType detect() { Optional<String> gaeEnvironment = getProperty(APP_ENGINE_ENVIRONMENT_PATH); if (gaeEnvironment.isPresent()) { if (APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE.equals(gaeEnvironment.get())) { return APPENGINE_EMULATOR; } if (APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE.equals(gaeEnvironment.get())) { return APPENGINE_CLOUD; } } return STANDALONE; } @SuppressWarnings("AccessOfSystemProperties") /* Based on system property. */ private static Optional<String> getProperty(String path) { return ofNullable(emptyToNull(System.getProperty(path))); } }
server/src/main/java/io/spine/server/DeploymentDetector.java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server; import com.google.common.annotations.VisibleForTesting; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import java.util.Optional; import java.util.function.Supplier; import static com.google.common.base.Strings.emptyToNull; import static io.spine.server.DeploymentType.APPENGINE_CLOUD; import static io.spine.server.DeploymentType.APPENGINE_EMULATOR; import static io.spine.server.DeploymentType.STANDALONE; import static java.util.Optional.ofNullable; /** * The default implementation of {@linkplain DeploymentType deployment type} * {@linkplain Supplier supplier}. */ class DeploymentDetector implements Supplier<DeploymentType> { @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_PATH = "com.google.appengine.runtime.environment"; @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE = "Production"; @VisibleForTesting static final String APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE = "Development"; private @MonotonicNonNull DeploymentType deploymentType; /** Prevent instantiation from outside. */ private DeploymentDetector() { } public static Supplier<DeploymentType> newInstance() { return new DeploymentDetector(); } @Override public DeploymentType get() { if (deploymentType == null) { deploymentType = detect(); } return deploymentType; } private static DeploymentType detect() { Optional<String> gaeEnvironment = getProperty(APP_ENGINE_ENVIRONMENT_PATH); if (gaeEnvironment.isPresent()) { if (APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE.equals(gaeEnvironment.get())) { return APPENGINE_EMULATOR; } if (APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE.equals(gaeEnvironment.get())) { return APPENGINE_CLOUD; } } return STANDALONE; } @SuppressWarnings("AccessOfSystemProperties") /* Based on system property. */ private static Optional<String> getProperty(String path) { return ofNullable(emptyToNull(System.getProperty(path))); } }
Remove redundant whitespaces.
server/src/main/java/io/spine/server/DeploymentDetector.java
Remove redundant whitespaces.
<ide><path>erver/src/main/java/io/spine/server/DeploymentDetector.java <ide> static final String APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE = "Production"; <ide> @VisibleForTesting <ide> static final String APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE = "Development"; <del> <add> <ide> private @MonotonicNonNull DeploymentType deploymentType; <ide> <ide> /** Prevent instantiation from outside. */
Java
mit
a1a52fca350e20c6c9d8328d8ea4bf42ffdcec8f
0
xSzymo/Chat-bot,xSzymo/Chat-bot,xSzymo/Chat-bot
package com.xszymo.hibernate.configuration; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import javax.annotation.PostConstruct; import javax.annotation.Resource; import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import com.xszymo.hibernate.interfaces.AnswersMessageService; import com.xszymo.hibernate.interfaces.QuestionsMessageService; import com.xszymo.hibernate.interfaces.UserService; import com.xszymo.hibernate.tables.Answer; import com.xszymo.hibernate.tables.Question; @Configuration public class LoadAtStart { public static final String PATH_QUESTIONS = "/home/xszymo/Desktop/Programming/text.txt"; public static final boolean readQuestionsAndAnswersFromTxt = true; @Resource(name = "answerMessageService") AnswersMessageService answer; @Resource(name = "questionMessageService") QuestionsMessageService question; @Autowired UserService userService; @PostConstruct public void halo() throws IOException { // String everything = ""; if (readQuestionsAndAnswersFromTxt) { File file = new File(PATH_QUESTIONS); if (!(file.exists() && !file.isDirectory())) { Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(PATH_QUESTIONS), "utf-8")); writer.write("Test -.|.- test :) "); if (writer != null) writer.close(); } try (BufferedReader br = new BufferedReader(new FileReader(PATH_QUESTIONS))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { boolean a = false; String hey = ""; String hey1 = ""; char[] chars = line.toCharArray(); for (int i = 0; i < chars.length; i++) { int k = i; if (chars[k++] == '-' && i < chars.length - 1) if (chars[k++] == '.') if (chars[k++] == '|') if (chars[k++] == '.') if (chars[k++] == '-') { a = true; i = k + 1; } if(i >= chars.length) i = chars.length-1; if (!a) hey += chars[i]; else hey1 += chars[i]; } Question questuerinio = new Question(hey.substring(0, hey.length()-1)); Answer answerino = null; if(!hey1.equals(" ")) { answerino = new Answer(hey1); answerino.setQuestion(questuerinio); questuerinio.getAnswers().add(answerino); } question.persist(questuerinio); if(!hey1.equals(" ")) { answer.persist(answerino); } line = br.readLine(); } sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); // everything = sb.toString(); } catch (IOException e) { e.printStackTrace(); } } } }
src/main/java/com/xszymo/hibernate/configuration/LoadAtStart.java
package com.xszymo.hibernate.configuration; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import com.xszymo.hibernate.interfaces.AnswersMessageService; import com.xszymo.hibernate.interfaces.QuestionsMessageService; import com.xszymo.hibernate.interfaces.UserService; import com.xszymo.hibernate.tables.Answer; import com.xszymo.hibernate.tables.Question; @Configuration public class LoadAtStart { public static final String PATH_QUESTIONS = "/home/xszymo/Desktop/Programming/text1.txt"; public static final boolean readQuestionsAndAnswersFromTxt = true; @Resource(name = "answerMessageService") AnswersMessageService answer; @Resource(name = "questionMessageService") QuestionsMessageService question; @Autowired UserService userService; @PostConstruct public void halo() throws IOException { // String everything = ""; if (readQuestionsAndAnswersFromTxt) { File file = new File(PATH_QUESTIONS); if (!(file.exists() && !file.isDirectory())) { Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(PATH_QUESTIONS), "utf-8")); writer.write("Test -.|.- test :) "); if (writer != null) writer.close(); } try (BufferedReader br = new BufferedReader(new FileReader(PATH_QUESTIONS))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { boolean a = false; String hey = ""; String hey1 = ""; char[] chars = line.toCharArray(); for (int i = 0; i < chars.length; i++) { int k = i; if (chars[k++] == '-' && i < chars.length - 1) if (chars[k++] == '.') if (chars[k++] == '|') if (chars[k++] == '.') if (chars[k++] == '-') { a = true; i = k + 1; } if (!a) hey += chars[i]; else hey1 += chars[i]; } Question questuerinio = new Question(hey.substring(0, hey.length() - 1)); Answer answerino = new Answer(hey1); answerino.setQuestion(questuerinio); questuerinio.getAnswers().add(answerino); question.persist(questuerinio); answer.persist(answerino); line = br.readLine(); } sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); // everything = sb.toString(); } catch (IOException e) { e.printStackTrace(); } } } }
fix a few bugs in loadAtStart
src/main/java/com/xszymo/hibernate/configuration/LoadAtStart.java
fix a few bugs in loadAtStart
<ide><path>rc/main/java/com/xszymo/hibernate/configuration/LoadAtStart.java <ide> package com.xszymo.hibernate.configuration; <add> <ide> <ide> import java.io.BufferedReader; <ide> import java.io.BufferedWriter; <ide> import java.io.FileNotFoundException; <ide> import java.io.FileOutputStream; <ide> import java.io.FileReader; <add>import java.io.FileWriter; <ide> import java.io.IOException; <ide> import java.io.OutputStreamWriter; <add>import java.io.PrintWriter; <ide> import java.io.UnsupportedEncodingException; <ide> import java.io.Writer; <ide> <ide> import javax.annotation.PostConstruct; <ide> import javax.annotation.Resource; <del> <add>import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Configuration; <del> <ide> import com.xszymo.hibernate.interfaces.AnswersMessageService; <ide> import com.xszymo.hibernate.interfaces.QuestionsMessageService; <ide> import com.xszymo.hibernate.interfaces.UserService; <ide> <ide> @Configuration <ide> public class LoadAtStart { <del> public static final String PATH_QUESTIONS = "/home/xszymo/Desktop/Programming/text1.txt"; <add> public static final String PATH_QUESTIONS = "/home/xszymo/Desktop/Programming/text.txt"; <ide> public static final boolean readQuestionsAndAnswersFromTxt = true; <ide> <ide> @Resource(name = "answerMessageService") <ide> a = true; <ide> i = k + 1; <ide> } <add> if(i >= chars.length) <add> i = chars.length-1; <add> <ide> if (!a) <ide> hey += chars[i]; <ide> else <ide> hey1 += chars[i]; <ide> } <del> Question questuerinio = new Question(hey.substring(0, hey.length() - 1)); <del> Answer answerino = new Answer(hey1); <add> Question questuerinio = new Question(hey.substring(0, hey.length()-1)); <add> Answer answerino = null; <add> if(!hey1.equals(" ")) { <add> answerino = new Answer(hey1); <ide> answerino.setQuestion(questuerinio); <ide> questuerinio.getAnswers().add(answerino); <add> } <ide> question.persist(questuerinio); <del> answer.persist(answerino); <add> if(!hey1.equals(" ")) { <add> answer.persist(answerino); <add> } <add> <ide> line = br.readLine(); <ide> } <ide>
Java
apache-2.0
92def00c21b602cb485bb2eed3415edc9115f915
0
neo4j/neo4j-java-driver,neo4j/neo4j-java-driver,neo4j/neo4j-java-driver,zhenlineo/java-driver
/** * Copyright (c) 2002-2015 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.driver.internal; import java.util.Collections; import java.util.Map; import org.neo4j.driver.Result; import org.neo4j.driver.Statement; import org.neo4j.driver.Transaction; import org.neo4j.driver.Value; import org.neo4j.driver.exceptions.ClientException; import org.neo4j.driver.exceptions.Neo4jException; import org.neo4j.driver.internal.spi.Connection; public class StandardTransaction implements Transaction { private final Connection conn; private final Runnable cleanup; private enum State { /** The transaction is running with no explicit success or failure marked */ ACTIVE, /** Running, user marked for success, meaning it'll get committed */ MARKED_SUCCESS, /** User marked as failed, meaning it'll be rolled back. */ MARKED_FAILED, /** * An error has occurred, transaction can no longer be used and no more messages will be sent for this * transaction. */ FAILED, /** This transaction has successfully committed */ SUCCEEDED, /** This transaction has been rolled back */ ROLLED_BACK } private State state = State.ACTIVE; public StandardTransaction( Connection conn, Runnable cleanup ) { this.conn = conn; this.cleanup = cleanup; // Note there is no sync here, so this will just get queued locally conn.run( "BEGIN", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); } @Override public void success() { if ( state == State.ACTIVE ) { state = State.MARKED_SUCCESS; } } @Override public void failure() { if ( state == State.ACTIVE || state == State.MARKED_SUCCESS ) { state = State.MARKED_FAILED; } } @Override public void close() { try { if ( state == State.MARKED_SUCCESS ) { conn.run( "COMMIT", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); conn.sync(); state = State.SUCCEEDED; } else if ( state == State.MARKED_FAILED || state == State.ACTIVE ) { // If alwaysValid of the things we've put in the queue have been sent off, there is no need to // do this, we could just clear the queue. Future optimization. conn.run( "ROLLBACK", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); state = State.ROLLED_BACK; } } finally { cleanup.run(); } } @Override @SuppressWarnings( "unchecked" ) public Result run( String statementText, Map<String,Value> parameters ) { ensureNotFailed(); try { ResultBuilder resultBuilder = new ResultBuilder( statementText, parameters ); conn.run( statementText, parameters, resultBuilder ); conn.pullAll( resultBuilder ); conn.sync(); return resultBuilder.build(); } catch ( Neo4jException e ) { state = State.FAILED; throw e; } } @Override public Result run( String statementText ) { return run( statementText, ParameterSupport.NO_PARAMETERS ); } @Override public Result run( Statement statement ) { return run( statement.text(), statement.parameters() ); } @Override public boolean isOpen() { return state == State.ACTIVE; } private void ensureNotFailed() { if ( state == State.FAILED ) { throw new ClientException( "Cannot run more statements in this transaction, because previous statements in the " + "transaction has failed and the transaction has been rolled back. Please start a new" + " transaction to run another statement." ); } } }
driver/src/main/java/org/neo4j/driver/internal/StandardTransaction.java
/** * Copyright (c) 2002-2015 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.driver.internal; import java.util.Collections; import java.util.Map; import javafx.print.Collation; import org.neo4j.driver.Result; import org.neo4j.driver.Statement; import org.neo4j.driver.Transaction; import org.neo4j.driver.Value; import org.neo4j.driver.exceptions.ClientException; import org.neo4j.driver.exceptions.Neo4jException; import org.neo4j.driver.internal.spi.Connection; import static java.util.Collections.EMPTY_MAP; public class StandardTransaction implements Transaction { private final Connection conn; private final Runnable cleanup; private enum State { /** The transaction is running with no explicit success or failure marked */ ACTIVE, /** Running, user marked for success, meaning it'll get committed */ MARKED_SUCCESS, /** User marked as failed, meaning it'll be rolled back. */ MARKED_FAILED, /** * An error has occurred, transaction can no longer be used and no more messages will be sent for this * transaction. */ FAILED, /** This transaction has successfully committed */ SUCCEEDED, /** This transaction has been rolled back */ ROLLED_BACK } private State state = State.ACTIVE; public StandardTransaction( Connection conn, Runnable cleanup ) { this.conn = conn; this.cleanup = cleanup; // Note there is no sync here, so this will just get queued locally conn.run( "BEGIN", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); } @Override public void success() { if ( state == State.ACTIVE ) { state = State.MARKED_SUCCESS; } } @Override public void failure() { if ( state == State.ACTIVE || state == State.MARKED_SUCCESS ) { state = State.MARKED_FAILED; } } @Override public void close() { try { if ( state == State.MARKED_SUCCESS ) { conn.run( "COMMIT", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); conn.sync(); state = State.SUCCEEDED; } else if ( state == State.MARKED_FAILED || state == State.ACTIVE ) { // If alwaysValid of the things we've put in the queue have been sent off, there is no need to // do this, we could just clear the queue. Future optimization. conn.run( "ROLLBACK", Collections.<String, Value>emptyMap(), null ); conn.discardAll(); state = State.ROLLED_BACK; } } finally { cleanup.run(); } } @Override @SuppressWarnings( "unchecked" ) public Result run( String statementText, Map<String,Value> parameters ) { ensureNotFailed(); try { ResultBuilder resultBuilder = new ResultBuilder( statementText, parameters ); conn.run( statementText, parameters, resultBuilder ); conn.pullAll( resultBuilder ); conn.sync(); return resultBuilder.build(); } catch ( Neo4jException e ) { state = State.FAILED; throw e; } } @Override public Result run( String statementText ) { return run( statementText, ParameterSupport.NO_PARAMETERS ); } @Override public Result run( Statement statement ) { return run( statement.text(), statement.parameters() ); } @Override public boolean isOpen() { return state == State.ACTIVE; } private void ensureNotFailed() { if ( state == State.FAILED ) { throw new ClientException( "Cannot run more statements in this transaction, because previous statements in the " + "transaction has failed and the transaction has been rolled back. Please start a new" + " transaction to run another statement." ); } } }
Fix wrong import
driver/src/main/java/org/neo4j/driver/internal/StandardTransaction.java
Fix wrong import
<ide><path>river/src/main/java/org/neo4j/driver/internal/StandardTransaction.java <ide> import java.util.Collections; <ide> import java.util.Map; <ide> <del>import javafx.print.Collation; <del> <ide> import org.neo4j.driver.Result; <ide> import org.neo4j.driver.Statement; <ide> import org.neo4j.driver.Transaction; <ide> import org.neo4j.driver.exceptions.ClientException; <ide> import org.neo4j.driver.exceptions.Neo4jException; <ide> import org.neo4j.driver.internal.spi.Connection; <del> <del>import static java.util.Collections.EMPTY_MAP; <ide> <ide> public class StandardTransaction implements Transaction <ide> {
Java
mit
2ee75ac79f40be550f1152f5d76587e3680243a9
0
AlmuraDev/MoreMaterials
/* The MIT License Copyright (c) 2011 Zloteanu Nichita (ZNickq) and Andre Mohren (IceReaper) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.morematerials.manager; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.Recipe; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.inventory.SpoutItemStack; import org.getspout.spoutapi.inventory.SpoutShapedRecipe; import org.getspout.spoutapi.inventory.SpoutShapelessRecipe; import org.getspout.spoutapi.material.Material; import org.getspout.spoutapi.material.MaterialData; import com.github.Zarklord1.FurnaceApi.FurnaceRecipes; import net.morematerials.MoreMaterials; import net.morematerials.materials.CustomShape; import net.morematerials.materials.MMCustomBlock; import net.morematerials.materials.MMCustomItem; import net.morematerials.materials.MMCustomTool; import net.morematerials.materials.MMLegacyMaterial; public class SmpManager { private MoreMaterials plugin; private ArrayList<MMCustomBlock> blocksList = new ArrayList<MMCustomBlock>(); private ArrayList<MMCustomItem> itemsList = new ArrayList<MMCustomItem>(); private ArrayList<MMCustomTool> toolsList = new ArrayList<MMCustomTool>(); private ArrayList<MMLegacyMaterial> legacyList = new ArrayList<MMLegacyMaterial>(); private ArrayList<CustomShape> shapesList = new ArrayList<CustomShape>(); public SmpManager(MoreMaterials plugin) { this.plugin = plugin; } public void init() { // Load all .smp files. File dir = new File(this.plugin.getDataFolder().getPath(), "materials"); for (File file : dir.listFiles()) { if (file.getName().endsWith(".smp")) { try { this.loadPackage(file); } catch (Exception exception) { this.plugin.getUtilsManager().log("Cannot load " + file.getName(), Level.SEVERE); } } } } private void loadPackage(File file) throws Exception { HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>(); ZipFile smpFile = new ZipFile(file); // Get all material configurations Enumeration<? extends ZipEntry> entries = smpFile.entries(); ZipEntry entry; YamlConfiguration yml; while (entries.hasMoreElements()) { entry = entries.nextElement(); // Parse all .yml files in this .smp file. if (entry.getName().endsWith(".yml")) { yml = new YamlConfiguration(); yml.load(smpFile.getInputStream(entry)); materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yml); } else if (entry.getName().endsWith(".shape")) { // Register .shape files. this.shapesList.add(new CustomShape(this.plugin, smpFile, entry)); } else { // Add all other files as asset. this.plugin.getWebManager().addAsset(smpFile, entry); } } // First loop - Create all materials. for (String matName : materials.keySet()) { this.createMaterial(this.plugin.getUtilsManager().getName(smpFile.getName()), matName, materials.get(matName), smpFile); } // Second loop - Now we can reference all drops for (Integer i = 0; i < this.blocksList.size(); i++) { this.blocksList.get(i).configureDrops(); } // Third loop - Now we can reference all crafting recipes for (String matName : materials.keySet()) { this.registerRecipes(this.plugin.getUtilsManager().getName(smpFile.getName()), matName, materials.get(matName)); } // At last load legacyrecipes.yml for compatibility this.loadLegacyRecipes(); } private void createMaterial(String smpName, String matName, YamlConfiguration yaml, ZipFile smpFile) { // Allow reading of old .smp files. if (!yaml.contains("Texture")) { yaml = this.updateConfiguration(yaml, smpName, matName); this.plugin.getUtilsManager().log("Please update " + matName + ".yml", Level.WARNING); } // Create the actual materials. if (matName.matches("^[0-9]+$")) { MMLegacyMaterial material = this.getLegacyMaterial(Integer.parseInt(matName)); if (material == null) { this.legacyList.add(new MMLegacyMaterial(yaml, smpName, matName)); } else { material.configureBase(smpName, yaml); } } else if (yaml.getString("Type", "").equals("Block")) { this.blocksList.add(MMCustomBlock.create(this.plugin, yaml, smpName, matName)); } else if (yaml.getString("Type", "").equals("Tool")) { this.toolsList.add(MMCustomTool.create(this.plugin, yaml, smpName, matName)); } else { this.itemsList.add(MMCustomItem.create(this.plugin, yaml, smpName, matName)); } } @Deprecated private YamlConfiguration updateConfiguration(YamlConfiguration yaml, String smpName, String matName) { // Update old .yml configurations to newer format. yaml.set("Texture", matName + ".png"); if (((String) yaml.get("Type")).equals("Block")) { yaml.set("Shape", matName + ".shape"); yaml.set("BaseId", yaml.get("BlockID")); // Creating the texture map list. ArrayList<String> coordList = new ArrayList<String>(); BufferedImage bufferedImage = this.plugin.getWebManager().getCachedImage(this.plugin.getWebManager().getAssetsUrl(smpName + "_" + matName + ".png")); if (bufferedImage.getWidth() > bufferedImage.getHeight()) { for (Integer i = 0; i < bufferedImage.getWidth() / bufferedImage.getHeight(); i++) { coordList.add(bufferedImage.getHeight() * i + " 0 " + bufferedImage.getHeight() + " " + bufferedImage.getHeight()); } } else { coordList.add("0 0 " + bufferedImage.getWidth() + " " + bufferedImage.getHeight()); } yaml.set("Coords", coordList); } return yaml; } public CustomShape getShape(String smpName, String matName) { CustomShape shape; // Search for the correct shape for (Integer i = 0; i < this.shapesList.size(); i++) { shape = this.shapesList.get(i); if (shape.getSmpName().equals(smpName)) { if (shape.getMatName().equals(matName)) { return shape; } } } return null; } public ArrayList<Material> getMaterial(String smpName, String matName) { return this.getMaterial(smpName + "." + matName); } public ArrayList<Material> getMaterial(String fullName) { String[] nameParts = fullName.split("\\."); ArrayList<Material> found = new ArrayList<Material>(); // First check for matching blocks. MMCustomBlock currentBlock; for (Integer i = 0; i < this.blocksList.size(); i++) { currentBlock = this.blocksList.get(i); if (nameParts.length == 1 && currentBlock.getMaterialName().equals(nameParts[0])) { found.add(currentBlock); } else if (currentBlock.getSmpName().equals(nameParts[0]) && currentBlock.getMaterialName().equals(nameParts[1])) { found.add(currentBlock); } } // Then also check for matching items. MMCustomItem currentItem; for (Integer i = 0; i < this.itemsList.size(); i++) { currentItem = this.itemsList.get(i); if (nameParts.length == 1 && currentItem.getMaterialName().equals(nameParts[0])) { found.add(currentItem); } else if (currentItem.getSmpName().equals(nameParts[0]) && currentItem.getMaterialName().equals(nameParts[1])) { found.add(currentItem); } } // Then also check for matching tools. MMCustomTool currentTool; for (Integer i = 0; i < this.toolsList.size(); i++) { currentTool = this.toolsList.get(i); if (nameParts.length == 1 && currentTool.getMaterialName().equals(nameParts[0])) { found.add(currentTool); } else if (currentTool.getSmpName().equals(nameParts[0]) && currentTool.getMaterialName().equals(nameParts[1])) { found.add(currentTool); } } return found; } public Material getMaterial(Integer materialId) { // First check for matching blocks. MMCustomBlock currentBlock; for (Integer i = 0; i < this.blocksList.size(); i++) { currentBlock = this.blocksList.get(i); if (currentBlock.getCustomId() == materialId) { return currentBlock; } } // Then also check for matching items. MMCustomItem currentItem; for (Integer i = 0; i < this.itemsList.size(); i++) { currentItem = this.itemsList.get(i); if (currentItem.getCustomId() == materialId) { return currentItem; } } // Then also check for matching tools. MMCustomTool currentTool; for (Integer i = 0; i < this.toolsList.size(); i++) { currentTool = this.toolsList.get(i); if (currentTool.getCustomId() == materialId) { return currentTool; } } return null; } public MMLegacyMaterial getLegacyMaterial(Integer materialId) { // Get correct legacy material. MMLegacyMaterial currentMaterial; for (Integer i = 0; i < this.legacyList.size(); i++) { currentMaterial = this.legacyList.get(i); if (currentMaterial.getMaterialId() == materialId) { return currentMaterial; } } return null; } private void registerRecipes(String smpName, String matName, YamlConfiguration config) { //TODO Unchecked cast warning remove List<YamlConfiguration> recipes = (List<YamlConfiguration>) config.getList("Recipes"); // Make sure we have a valid list. if (recipes == null) { return; } // Get the material object which we want to craft. Material material; if (matName.matches("^[0-9]+$")) { material = this.getMaterial(Integer.parseInt(matName)); } else { material = this.getMaterial(smpName, matName).get(0); } for (YamlConfiguration recipe : recipes) { // This is what we want to craft. Integer amount = recipe.getInt("Amount", 1); SpoutItemStack stack = new SpoutItemStack(material, amount); String ingredients = recipe.getString("Ingredients"); // Building recipe String type = recipe.getString("Type"); if (type.equalsIgnoreCase("Furnace")) { // Easy furnace stuff :D Material ingredient; if (ingredients.matches("^[0-9]+$")) { ingredient = MaterialData.getMaterial(Integer.parseInt(ingredients)); } else { ingredient = this.getMaterial(smpName, matName).get(0); } //TODO figure out why we need param2 and param3 FurnaceRecipes.CustomFurnaceRecipe(new SpoutItemStack(material, amount), ingredient.getRawId(), ingredient.getRawData()); } else { Recipe sRecipe = null; // Get recipe type. if (type.equalsIgnoreCase("Shapeless")) { sRecipe = new SpoutShapelessRecipe(stack); } else if (type.equalsIgnoreCase("Shaped")) { sRecipe = new SpoutShapedRecipe(stack).shape("abc","def", "ghi"); } // Split ingredients. ingredients = ingredients.replaceAll("\\s{2,}", " "); // Parse all lines Integer currentLine = 0; Integer currentColumn = 0; for (String line : ingredients.split("\\r?\\n")) { for (String ingredientitem : line.split(" ")) { // Skip "air" if (ingredientitem.equals("0")) { currentColumn++; continue; } // Get correct ingredient material Material ingredient; if (ingredients.matches("^[0-9]+$")) { ingredient = MaterialData.getMaterial(Integer.parseInt(ingredients)); } else { ingredient = this.getMaterial(smpName, matName).get(0); } // Add the ingredient if (sRecipe instanceof SpoutShapedRecipe) { char a = (char) ('a' + currentColumn + currentLine * 3); ((SpoutShapedRecipe) sRecipe).setIngredient(a, ingredient); } else { ((SpoutShapelessRecipe) sRecipe).addIngredient(ingredient); } } } // Finaly register recipe. SpoutManager.getMaterialManager().registerSpoutRecipe(sRecipe); } } } @Deprecated private void loadLegacyRecipes() { //TODO just load it :D } }
src/main/java/net/morematerials/manager/SmpManager.java
/* The MIT License Copyright (c) 2011 Zloteanu Nichita (ZNickq) and Andre Mohren (IceReaper) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.morematerials.manager; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.configuration.file.YamlConfiguration; import org.getspout.spoutapi.material.Material; import net.morematerials.MoreMaterials; import net.morematerials.materials.CustomShape; import net.morematerials.materials.MMCustomBlock; import net.morematerials.materials.MMCustomItem; import net.morematerials.materials.MMCustomTool; import net.morematerials.materials.MMLegacyMaterial; public class SmpManager { private MoreMaterials plugin; private ArrayList<MMCustomBlock> blocksList = new ArrayList<MMCustomBlock>(); private ArrayList<MMCustomItem> itemsList = new ArrayList<MMCustomItem>(); private ArrayList<MMCustomTool> toolsList = new ArrayList<MMCustomTool>(); private ArrayList<MMLegacyMaterial> legacyList = new ArrayList<MMLegacyMaterial>(); private ArrayList<CustomShape> shapesList = new ArrayList<CustomShape>(); public SmpManager(MoreMaterials plugin) { this.plugin = plugin; } public void init() { // Load all .smp files. File dir = new File(this.plugin.getDataFolder().getPath(), "materials"); for (File file : dir.listFiles()) { if (file.getName().endsWith(".smp")) { try { this.loadPackage(file); } catch (Exception exception) { this.plugin.getUtilsManager().log("Cannot load " + file.getName(), Level.SEVERE); } } } } private void loadPackage(File file) throws Exception { HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>(); ZipFile smpFile = new ZipFile(file); // Get all material configurations Enumeration<? extends ZipEntry> entries = smpFile.entries(); ZipEntry entry; YamlConfiguration yml; while (entries.hasMoreElements()) { entry = entries.nextElement(); // Parse all .yml files in this .smp file. if (entry.getName().endsWith(".yml")) { yml = new YamlConfiguration(); yml.load(smpFile.getInputStream(entry)); materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yml); } else if (entry.getName().endsWith(".shape")) { // Register .shape files. this.shapesList.add(new CustomShape(this.plugin, smpFile, entry)); } else { // Add all other files as asset. this.plugin.getWebManager().addAsset(smpFile, entry); } } // First loop - Create all materials. for (String matName : materials.keySet()) { this.createMaterial(this.plugin.getUtilsManager().getName(smpFile.getName()), matName, materials.get(matName), smpFile); } // Second loop - Now we can reference all drops for (Integer i = 0; i < this.blocksList.size(); i++) { this.blocksList.get(i).configureDrops(); } } private void createMaterial(String smpName, String matName, YamlConfiguration yaml, ZipFile smpFile) { // Allow reading of old .smp files. if (!yaml.contains("Texture")) { yaml = this.updateConfiguration(yaml, smpName, matName); this.plugin.getUtilsManager().log("Please update " + matName + ".yml", Level.WARNING); } // Create the actual materials. if (matName.matches("^[0-9]+$")) { MMLegacyMaterial material = this.getLegacyMaterial(Integer.parseInt(matName)); if (material == null) { this.legacyList.add(new MMLegacyMaterial(yaml, smpName, matName)); } else { material.configureBase(smpName, yaml); } } else if (yaml.getString("Type", "").equals("Block")) { this.blocksList.add(MMCustomBlock.create(this.plugin, yaml, smpName, matName)); } else if (yaml.getString("Type", "").equals("Tool")) { this.toolsList.add(MMCustomTool.create(this.plugin, yaml, smpName, matName)); } else { this.itemsList.add(MMCustomItem.create(this.plugin, yaml, smpName, matName)); } } @Deprecated private YamlConfiguration updateConfiguration(YamlConfiguration yaml, String smpName, String matName) { // Update old .yml configurations to newer format. yaml.set("Texture", matName + ".png"); if (((String) yaml.get("Type")).equals("Block")) { yaml.set("Shape", matName + ".shape"); yaml.set("BaseId", yaml.get("BlockID")); // Creating the texture map list. ArrayList<String> coordList = new ArrayList<String>(); BufferedImage bufferedImage = this.plugin.getWebManager().getCachedImage(this.plugin.getWebManager().getAssetsUrl(smpName + "_" + matName + ".png")); if (bufferedImage.getWidth() > bufferedImage.getHeight()) { for (Integer i = 0; i < bufferedImage.getWidth() / bufferedImage.getHeight(); i++) { coordList.add(bufferedImage.getHeight() * i + " 0 " + bufferedImage.getHeight() + " " + bufferedImage.getHeight()); } } else { coordList.add("0 0 " + bufferedImage.getWidth() + " " + bufferedImage.getHeight()); } yaml.set("Coords", coordList); } return yaml; } public CustomShape getShape(String smpName, String matName) { CustomShape shape; // Search for the correct shape for (Integer i = 0; i < this.shapesList.size(); i++) { shape = this.shapesList.get(i); if (shape.getSmpName().equals(smpName)) { if (shape.getMatName().equals(matName)) { return shape; } } } return null; } public ArrayList<Material> getMaterial(String smpName, String matName) { return this.getMaterial(smpName + "." + matName); } public ArrayList<Material> getMaterial(String fullName) { String[] nameParts = fullName.split("\\."); ArrayList<Material> found = new ArrayList<Material>(); // First check for matching blocks. MMCustomBlock currentBlock; for (Integer i = 0; i < this.blocksList.size(); i++) { currentBlock = this.blocksList.get(i); if (nameParts.length == 1 && currentBlock.getMaterialName().equals(nameParts[0])) { found.add(currentBlock); } else if (currentBlock.getSmpName().equals(nameParts[0]) && currentBlock.getMaterialName().equals(nameParts[1])) { found.add(currentBlock); } } // Then also check for matching items. MMCustomItem currentItem; for (Integer i = 0; i < this.itemsList.size(); i++) { currentItem = this.itemsList.get(i); if (nameParts.length == 1 && currentItem.getMaterialName().equals(nameParts[0])) { found.add(currentItem); } else if (currentItem.getSmpName().equals(nameParts[0]) && currentItem.getMaterialName().equals(nameParts[1])) { found.add(currentItem); } } // Then also check for matching tools. MMCustomTool currentTool; for (Integer i = 0; i < this.toolsList.size(); i++) { currentTool = this.toolsList.get(i); if (nameParts.length == 1 && currentTool.getMaterialName().equals(nameParts[0])) { found.add(currentTool); } else if (currentTool.getSmpName().equals(nameParts[0]) && currentTool.getMaterialName().equals(nameParts[1])) { found.add(currentTool); } } return found; } public Material getMaterial(Integer materialId) { // First check for matching blocks. MMCustomBlock currentBlock; for (Integer i = 0; i < this.blocksList.size(); i++) { currentBlock = this.blocksList.get(i); if (currentBlock.getCustomId() == materialId) { return currentBlock; } } // Then also check for matching items. MMCustomItem currentItem; for (Integer i = 0; i < this.itemsList.size(); i++) { currentItem = this.itemsList.get(i); if (currentItem.getCustomId() == materialId) { return currentItem; } } // Then also check for matching tools. MMCustomTool currentTool; for (Integer i = 0; i < this.toolsList.size(); i++) { currentTool = this.toolsList.get(i); if (currentTool.getCustomId() == materialId) { return currentTool; } } return null; } public MMLegacyMaterial getLegacyMaterial(Integer materialId) { // Get correct legacy material. MMLegacyMaterial currentMaterial; for (Integer i = 0; i < this.legacyList.size(); i++) { currentMaterial = this.legacyList.get(i); if (currentMaterial.getMaterialId() == materialId) { return currentMaterial; } } return null; } }
- Reimplement crafting recipes.
src/main/java/net/morematerials/manager/SmpManager.java
- Reimplement crafting recipes.
<ide><path>rc/main/java/net/morematerials/manager/SmpManager.java <ide> import java.util.ArrayList; <ide> import java.util.Enumeration; <ide> import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <ide> import java.util.logging.Level; <ide> import java.util.zip.ZipEntry; <ide> import java.util.zip.ZipFile; <ide> <ide> import org.bukkit.configuration.file.YamlConfiguration; <add>import org.bukkit.inventory.Recipe; <add>import org.getspout.spoutapi.SpoutManager; <add>import org.getspout.spoutapi.inventory.SpoutItemStack; <add>import org.getspout.spoutapi.inventory.SpoutShapedRecipe; <add>import org.getspout.spoutapi.inventory.SpoutShapelessRecipe; <ide> import org.getspout.spoutapi.material.Material; <add>import org.getspout.spoutapi.material.MaterialData; <add> <add>import com.github.Zarklord1.FurnaceApi.FurnaceRecipes; <ide> <ide> import net.morematerials.MoreMaterials; <ide> import net.morematerials.materials.CustomShape; <ide> for (Integer i = 0; i < this.blocksList.size(); i++) { <ide> this.blocksList.get(i).configureDrops(); <ide> } <add> <add> // Third loop - Now we can reference all crafting recipes <add> for (String matName : materials.keySet()) { <add> this.registerRecipes(this.plugin.getUtilsManager().getName(smpFile.getName()), matName, materials.get(matName)); <add> } <add> <add> // At last load legacyrecipes.yml for compatibility <add> this.loadLegacyRecipes(); <ide> } <ide> <ide> private void createMaterial(String smpName, String matName, YamlConfiguration yaml, ZipFile smpFile) { <ide> return null; <ide> } <ide> <add> private void registerRecipes(String smpName, String matName, YamlConfiguration config) { <add> //TODO Unchecked cast warning remove <add> List<YamlConfiguration> recipes = (List<YamlConfiguration>) config.getList("Recipes"); <add> // Make sure we have a valid list. <add> if (recipes == null) { <add> return; <add> } <add> <add> // Get the material object which we want to craft. <add> Material material; <add> if (matName.matches("^[0-9]+$")) { <add> material = this.getMaterial(Integer.parseInt(matName)); <add> } else { <add> material = this.getMaterial(smpName, matName).get(0); <add> } <add> <add> for (YamlConfiguration recipe : recipes) { <add> // This is what we want to craft. <add> Integer amount = recipe.getInt("Amount", 1); <add> SpoutItemStack stack = new SpoutItemStack(material, amount); <add> String ingredients = recipe.getString("Ingredients"); <add> <add> // Building recipe <add> String type = recipe.getString("Type"); <add> if (type.equalsIgnoreCase("Furnace")) { <add> // Easy furnace stuff :D <add> Material ingredient; <add> if (ingredients.matches("^[0-9]+$")) { <add> ingredient = MaterialData.getMaterial(Integer.parseInt(ingredients)); <add> } else { <add> ingredient = this.getMaterial(smpName, matName).get(0); <add> } <add> //TODO figure out why we need param2 and param3 <add> FurnaceRecipes.CustomFurnaceRecipe(new SpoutItemStack(material, amount), ingredient.getRawId(), ingredient.getRawData()); <add> } else { <add> Recipe sRecipe = null; <add> // Get recipe type. <add> if (type.equalsIgnoreCase("Shapeless")) { <add> sRecipe = new SpoutShapelessRecipe(stack); <add> } else if (type.equalsIgnoreCase("Shaped")) { <add> sRecipe = new SpoutShapedRecipe(stack).shape("abc","def", "ghi"); <add> } <add> <add> // Split ingredients. <add> ingredients = ingredients.replaceAll("\\s{2,}", " "); <add> <add> // Parse all lines <add> Integer currentLine = 0; <add> Integer currentColumn = 0; <add> for (String line : ingredients.split("\\r?\\n")) { <add> for (String ingredientitem : line.split(" ")) { <add> // Skip "air" <add> if (ingredientitem.equals("0")) { <add> currentColumn++; <add> continue; <add> } <add> <add> // Get correct ingredient material <add> Material ingredient; <add> if (ingredients.matches("^[0-9]+$")) { <add> ingredient = MaterialData.getMaterial(Integer.parseInt(ingredients)); <add> } else { <add> ingredient = this.getMaterial(smpName, matName).get(0); <add> } <add> <add> // Add the ingredient <add> if (sRecipe instanceof SpoutShapedRecipe) { <add> char a = (char) ('a' + currentColumn + currentLine * 3); <add> ((SpoutShapedRecipe) sRecipe).setIngredient(a, ingredient); <add> } else { <add> ((SpoutShapelessRecipe) sRecipe).addIngredient(ingredient); <add> } <add> } <add> } <add> // Finaly register recipe. <add> SpoutManager.getMaterialManager().registerSpoutRecipe(sRecipe); <add> } <add> } <add> } <add> <add> @Deprecated <add> private void loadLegacyRecipes() { <add> //TODO just load it :D <add> } <add> <ide> }
JavaScript
mit
a61bf2176f4888c14b2ab322655e68f6b865390a
0
stevecochrane/stevecochrane.com,stevecochrane/stevecochrane.com
var autoprefixer = require("autoprefixer"); var calc = require("postcss-calc"); var colorFunction = require("postcss-color-function"); var concat = require("gulp-concat"); var cssnano = require("cssnano"); var customMedia = require("postcss-custom-media"); var customProperties = require("postcss-custom-properties"); var del = require("del"); var gulp = require("gulp"); var imagemin = require("gulp-imagemin"); var jade = require("gulp-jade"); var jshint = require("gulp-jshint"); var nested = require("postcss-nested"); var pxtorem = require("postcss-pxtorem"); var postcss = require("gulp-postcss"); var postcssImport = require("postcss-import"); var postcssUrl = require("postcss-url"); var rev = require("gulp-rev"); var revReplace = require("gulp-rev-replace"); var stylelint = require("gulp-stylelint"); var uglify = require("gulp-uglify"); gulp.task("clean", function() { return del([ "dist/css/*.css", "dist/js/*.js" ]); }); gulp.task("images", function() { return gulp.src("src/img/**/*") .pipe(imagemin({ svgoPlugins: [ {removeViewBox: false}, {cleanupIDs: false} ] })) .pipe(gulp.dest("dist/img")); }); gulp.task("css", ["clean"], function() { return gulp.src([ "src/css/main.css", "src/css/portfolio.css" ]) .pipe(stylelint({ reporters: [ { console: true, formatter: "string" } ] })) .pipe(postcss([ postcssImport(), customProperties(), customMedia(), calc(), nested(), colorFunction(), pxtorem({ // Apply pxtorem to all style properties. propWhiteList: [] }), postcssUrl({ url: "inline" }), autoprefixer(), cssnano() ])) .pipe(gulp.dest("dist/css")); }); gulp.task("js-lint", function() { return gulp.src("src/js/*.js") .pipe(jshint()) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")); }); gulp.task("js-build-home", ["clean", "js-lint"], function() { return gulp.src("src/js/main.js") .pipe(uglify()) .pipe(gulp.dest("dist/js/")); }); gulp.task("js-build-portfolio", ["clean", "js-lint"], function() { return gulp.src([ "src/js/lib/jquery-2.0.3.min.js", "src/js/lib/jquery.lazyload.min.js", "src/js/portfolio-main.js" ]) .pipe(concat("portfolio-main.js")) .pipe(uglify()) .pipe(gulp.dest("dist/js/")); }); gulp.task("html", function() { // Normally the locals would be out of Gulp and in a controller but this site is otherwise all static. var dateObj = new Date(); var currentYear = dateObj.getFullYear(); return gulp.src("src/views/pages/**/*.jade") .pipe(jade({ "locals": { "currentYear": currentYear } })) .pipe(gulp.dest("dist/")); }); gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() { return gulp.src([ "dist/**/*.css", "dist/**/*.js" ]) .pipe(rev()) .pipe(gulp.dest("dist")) .pipe(rev.manifest()) .pipe(gulp.dest("dist")); }); gulp.task("revisionReplace", ["revision"], function() { var manifest = gulp.src("dist/rev-manifest.json"); return gulp.src("dist/**/*.html") .pipe(revReplace({"manifest": manifest})) .pipe(gulp.dest("dist")); }); gulp.task("default", [ "clean", "images", "css", "js-lint", "js-build-home", "js-build-portfolio", "html", "revision", "revisionReplace" ]);
gulpfile.js
var autoprefixer = require("autoprefixer"); var calc = require("postcss-calc"); var colorFunction = require("postcss-color-function"); var concat = require("gulp-concat"); var cssnano = require("cssnano"); var customMedia = require("postcss-custom-media"); var customProperties = require("postcss-custom-properties"); var del = require("del"); var gulp = require("gulp"); var imagemin = require("gulp-imagemin"); var jade = require("gulp-jade"); var jshint = require("gulp-jshint"); var nested = require("postcss-nested"); var pxtorem = require("postcss-pxtorem"); var postcss = require("gulp-postcss"); var postcssImport = require("postcss-import"); var postcssUrl = require("postcss-url"); var rev = require("gulp-rev"); var revReplace = require("gulp-rev-replace"); var stylelint = require("gulp-stylelint"); var uglify = require("gulp-uglify"); gulp.task("clean", function() { return del([ "dist/css/*.css", "dist/js/*.js" ]); }); gulp.task("images", function() { return gulp.src("src/img/**/*") .pipe(imagemin({ svgoPlugins: [ {removeViewBox: false}, {cleanupIDs: false} ] })) .pipe(gulp.dest("dist/img")); }); gulp.task("css", ["clean"], function() { return gulp.src([ "src/css/main.css", "src/css/portfolio.css" ]) .pipe(stylelint({ reporters: [ { console: true, formatter: "string" } ] })) .pipe(postcss([ postcssImport(), customProperties(), customMedia(), calc(), nested(), colorFunction(), pxtorem({ // Apply pxtorem to all style properties. propWhiteList: [] }), postcssUrl({ url: "inline" }), autoprefixer(), cssnano() ])) .pipe(gulp.dest("dist/css")); }); gulp.task("js-lint", function() { return gulp.src("src/js/*.js") .pipe(jshint()) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")); }); gulp.task("js-build-home", ["clean", "js-lint"], function() { return gulp.src([ "src/js/lib/jquery-1.7.2.min.js", "src/js/main.js" ]) .pipe(concat("main.js")) .pipe(uglify()) .pipe(gulp.dest("dist/js/")); }); gulp.task("js-build-portfolio", ["clean", "js-lint"], function() { return gulp.src([ "src/js/lib/jquery-2.0.3.min.js", "src/js/lib/jquery.lazyload.min.js", "src/js/portfolio-main.js" ]) .pipe(concat("portfolio-main.js")) .pipe(uglify()) .pipe(gulp.dest("dist/js/")); }); gulp.task("html", function() { // Normally the locals would be out of Gulp and in a controller but this site is otherwise all static. var dateObj = new Date(); var currentYear = dateObj.getFullYear(); return gulp.src("src/views/pages/**/*.jade") .pipe(jade({ "locals": { "currentYear": currentYear } })) .pipe(gulp.dest("dist/")); }); gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() { return gulp.src([ "dist/**/*.css", "dist/**/*.js" ]) .pipe(rev()) .pipe(gulp.dest("dist")) .pipe(rev.manifest()) .pipe(gulp.dest("dist")); }); gulp.task("revisionReplace", ["revision"], function() { var manifest = gulp.src("dist/rev-manifest.json"); return gulp.src("dist/**/*.html") .pipe(revReplace({"manifest": manifest})) .pipe(gulp.dest("dist")); }); gulp.task("default", [ "clean", "images", "css", "js-lint", "js-build-home", "js-build-portfolio", "html", "revision", "revisionReplace" ]);
Removed the jQuery dependency from the js-build-home task.
gulpfile.js
Removed the jQuery dependency from the js-build-home task.
<ide><path>ulpfile.js <ide> }); <ide> <ide> gulp.task("js-build-home", ["clean", "js-lint"], function() { <del> return gulp.src([ <del> "src/js/lib/jquery-1.7.2.min.js", <del> "src/js/main.js" <del> ]) <del> .pipe(concat("main.js")) <add> return gulp.src("src/js/main.js") <ide> .pipe(uglify()) <ide> .pipe(gulp.dest("dist/js/")); <ide> });
JavaScript
mit
f24774e54b9cd48ebe11ff61013582b62346c9ab
0
jagannath93/File-Management-System,jagannath93/File-Management-System
$(document).ready(function() { $(".filter1").on("change", function(){ if(!($(this).val() == '')) { var cat_data = {cat: $(this).val()}; $.get('/fms/get_sc1/', cat_data, function(res){ if(res.length) { var _filter2 = '<td class="filter2box"><select class="filter2">'+ '<option value="">SubCategory-1</option>'; for(var i=0; i<res.length; i++) { _filter2 += '<option value="'+res[i].code+'">'+res[i].name+'</option>'; } _filter2 += '</select></td>'; if($('.filter2box')) { $('.filter2box').remove(); } if($('.filter3box')) { $('.filter3box').remove(); } $(_filter2).appendTo('.filter-box'); } }); } else { if($('.filter2box')) { $('.filter2box').remove(); } if($('.filter3box')) { $('.filter3box').remove(); } } }); $(document).on("change", ".filter2", function(){ if(!($(this).val() == '')) { var cat_data = {cat: $('.filter1').val(), subcat1: $(this).val()}; $.get('/fms/get_sc2/', cat_data, function(res){ if(res.length) { var _filter3 = '<td class="filter3box"><select class="filter3">'+ '<option value="">SubCategory-2</option>'; for(var i=0; i<res.length; i++) { _filter3 += '<option value="'+res[i].code+'">'+res[i].name+'</option>'; } _filter3 += '</select></td>'; if($('.filter3box')) { $('.filter3box').remove(); } $(_filter3).appendTo('.filter-box'); } else { if($('.filter3box')) { $('.filter3box').remove(); } } }); } else { if($('.filter3box')) { $('.filter3box').remove(); } } }); //$(".collapse").collapse(); $(document).on("show", ".collapse", function(){ console.log("cp-1"); var ele_id = $(this).attr("id"); var id = ele_id.replace("doc-location-", ""); $("#location-btn-"+id).text("Hide Document Location") var url = $(this).attr('img-url'); var content = "<img src='"+ url +"' alt='Document Location Image' />"; $(this).html(content); }); $(document).on("hide", ".collapse", function(){ console.log("cp-2"); var ele_id = $(this).attr("id"); var id = ele_id.replace("doc-location-", ""); $("#location-btn-"+id).text("Show Document Location") }); /* ON BUTTON CLICK */ $('.get_list_btn').click(function(){ $(this).popover({ title: 'Loading Data..... Please Wait', html:true}); var filter_data = { filter1: $(".filter1").val(), filter2: $(".filter2").val(), filter3: $(".filter3").val() }; $.get('/fms/document/list/', filter_data, function(res){ $('.get_list_btn').popover('hide'); var ele = ''; for(var i=0; i<res.length; i++) { var _status = (res[i]._status == true) ? '<span style="color:green;"><b>YES<b></span>' : '<span style="color:red;"><b>No</b></span>'; var _subcat1 = (res[i].subcat1.name != undefined) ? res[i].subcat1.name:"--"; var _subcat2 = (res[i].subcat2.name != undefined) ? res[i].subcat2.name:"--"; var _rack_name = (res[i].rack.name != undefined) ? res[i].rack.name:"--"; var _rack_type = (res[i].rack.type != undefined) ? res[i].rack.type:"--"; ele += '<div class="doc-data">'+ '<legend>'+ res[i].name +'</legend>'+ '<table class="entry-table table table-striped table-bordered table-condensed">'+ '<tr>'+ '<td>'+ '<div class="doc-table">'+ '<table class="table table-striped table-bordered table-condensed">'+ '<tr><td>Name: </td><td>'+ res[i].name +'</td></tr>'+ '<tr><td>Address: </td><td>'+ res[i].address +'</td></tr>'+ '<tr><td>Category: </td><td>'+ res[i].cat.name +'</td></tr>'+ '<tr><td>SubCategory-1: </td><td>'+ _subcat1 +'</td></tr>'+ '<tr><td>SubCategory-2: </td><td>'+ _subcat2 +'</td></tr>'+ '<tr><td>Rack: </td><td>'+ _rack_name +'</td></tr>'+ '<tr><td>Rack type: </td><td>'+ _rack_type +'</td></tr>'+ '<tr><td>Availability: </td><td>'+ _status +'</td></tr>'+ '</table>'+ '</div>'+ '</td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<button type="button" id="location-btn-'+ res[i].id +'" class="btn" data-toggle="collapse" data-target="#doc-location-'+ res[i].id +'">Show Document Location</h5>'+ '</td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<div id="doc-location-'+ res[i].id +'" class="collapse" img-url="/'+ res[i].image_url +'"></div>'+ '</td>'+ '</tr>'+ '</table>'+ '</div><br>'; } $('#main').html(ele); }); }); });
static/js/doc-list.js
$(document).ready(function() { $(".filter1").on("change", function(){ if(!($(this).val() == '')) { var cat_data = {cat: $(this).val()}; $.get('/fms/get_sc1/', cat_data, function(res){ if(res.length) { var _filter2 = '<td class="filter2box"><select class="filter2">'+ '<option value="">SubCategory-1</option>'; for(var i=0; i<res.length; i++) { _filter2 += '<option value="'+res[i].code+'">'+res[i].name+'</option>'; } _filter2 += '</select></td>'; if($('.filter2box')) { $('.filter2box').remove(); } if($('.filter3box')) { $('.filter3box').remove(); } $(_filter2).appendTo('.filter-box'); } }); } else { if($('.filter2box')) { $('.filter2box').remove(); } if($('.filter3box')) { $('.filter3box').remove(); } } }); $(document).on("change", ".filter2", function(){ if(!($(this).val() == '')) { var cat_data = {cat: $('.filter1').val(), subcat1: $(this).val()}; $.get('/fms/get_sc2/', cat_data, function(res){ if(res.length) { var _filter3 = '<td class="filter3box"><select class="filter3">'+ '<option value="">SubCategory-2</option>'; for(var i=0; i<res.length; i++) { _filter3 += '<option value="'+res[i].code+'">'+res[i].name+'</option>'; } _filter3 += '</select></td>'; if($('.filter3box')) { $('.filter3box').remove(); } $(_filter3).appendTo('.filter-box'); } else { if($('.filter3box')) { $('.filter3box').remove(); } } }); } else { if($('.filter3box')) { $('.filter3box').remove(); } } }); $(".collapse").on("show", function(){ var ele_id = $(this).attr("id"); var id = ele_id.replace("doc-location-", ""); $("#location-btn-"+id).text("Hide Document Location") var url = $(this).attr('img-url'); var content = "<img src='"+ url +"' alt='Document Location Image' />"; $(this).html(content); }); $(".collapse").on("hide", function(){ var ele_id = $(this).attr("id"); var id = ele_id.replace("doc-location-", ""); $("#location-btn-"+id).text("Show Document Location") }); /* ON BUTTON CLICK */ $('.get_list_btn').click(function(){ $(this).popover({ title: 'Loading Data..... Please Wait', html:true}); var filter_data = { filter1: $(".filter1").val(), filter2: $(".filter2").val(), filter3: $(".filter3").val() }; $.get('/fms/document/list/', filter_data, function(res){ $('.get_list_btn').popover('hide'); var ele = ''; for(var i=0; i<res.length; i++) { var _status = (res[i]._status == true) ? '<span style="color:green;"><b>YES<b></span>' : '<span style="color:red;"><b>No</b></span>'; var _subcat1 = (res[i].subcat1.name != undefined) ? res[i].subcat1.name:"--"; var _subcat2 = (res[i].subcat2.name != undefined) ? res[i].subcat2.name:"--"; var _rack_name = (res[i].rack.name != undefined) ? res[i].rack.name:"--"; var _rack_type = (res[i].rack.type != undefined) ? res[i].rack.type:"--"; ele += '<div class="doc-data">'+ '<legend>'+ res[i].name +'</legend>'+ '<table class="entry-table table table-striped table-bordered table-condensed">'+ '<tr>'+ '<td>'+ '<div class="doc-table">'+ '<table class="table table-striped table-bordered table-condensed">'+ '<tr><td>Name: </td><td>'+ res[i].name +'</td></tr>'+ '<tr><td>Address: </td><td>'+ res[i].address +'</td></tr>'+ '<tr><td>Category: </td><td>'+ res[i].cat.name +'</td></tr>'+ '<tr><td>SubCategory-1: </td><td>'+ _subcat1 +'</td></tr>'+ '<tr><td>SubCategory-2: </td><td>'+ _subcat2 +'</td></tr>'+ '<tr><td>Rack: </td><td>'+ _rack_name +'</td></tr>'+ '<tr><td>Rack type: </td><td>'+ _rack_type +'</td></tr>'+ '<tr><td>Availability: </td><td>'+ _status +'</td></tr>'+ '</table>'+ '</div>'+ '</td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<button type="button" id="location-btn-'+ res[i].id +'" class="btn" data-toggle="collapse" data-target="#doc-location-'+ res[i].id +'">Show Document Location</h5>'+ '</td>'+ '</tr>'+ '<tr>'+ '<td>'+ '<div id="doc-location-'+ res[i].id +'" class="collapse" img-url="/'+ res[i].image_url +'"></div>'+ '</td>'+ '</tr>'+ '</table>'+ '</div><br>'; } $('#main').html(ele); }) }); });
Accordian ajax content bug fix
static/js/doc-list.js
Accordian ajax content bug fix
<ide><path>tatic/js/doc-list.js <ide> } <ide> }); <ide> <del> $(".collapse").on("show", function(){ <add> //$(".collapse").collapse(); <add> <add> $(document).on("show", ".collapse", function(){ <add> console.log("cp-1"); <ide> var ele_id = $(this).attr("id"); <ide> var id = ele_id.replace("doc-location-", ""); <ide> $("#location-btn-"+id).text("Hide Document Location") <ide> $(this).html(content); <ide> }); <ide> <del> $(".collapse").on("hide", function(){ <add> $(document).on("hide", ".collapse", function(){ <add> console.log("cp-2"); <ide> var ele_id = $(this).attr("id"); <ide> var id = ele_id.replace("doc-location-", ""); <ide> $("#location-btn-"+id).text("Show Document Location") <ide> <ide> } <ide> $('#main').html(ele); <del> }) <add> }); <ide> }); <ide> });
Java
apache-2.0
8775a96f5d7e596e9056c38c5761933d9894cc29
0
perbone/udao
/* * This file is part of UDAO * https://github.com/perbone/udao/ * * Copyright 2013-2017 Paulo Perbone * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package io.perbone.udao.provider.jdbc; import static io.perbone.udao.provider.jdbc.SqlDialect.DERBY; import static io.perbone.udao.provider.jdbc.SqlDialect.MYSQL; import static io.perbone.udao.provider.jdbc.SqlDialect.ORACLE; import static io.perbone.udao.provider.jdbc.SqlDialect.POSTGRESQL; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import io.perbone.toolbox.collection.Pair; import io.perbone.toolbox.provider.NotEnoughResourceException; import io.perbone.toolbox.provider.OperationTimeoutException; import io.perbone.toolbox.validation.StringValidations; import io.perbone.udao.Cursor; import io.perbone.udao.DataConstraintViolationException; import io.perbone.udao.KeyViolationException; import io.perbone.udao.NotFoundException; import io.perbone.udao.annotation.DataType; import io.perbone.udao.query.Expression; import io.perbone.udao.query.NativeQuery; import io.perbone.udao.query.Query; import io.perbone.udao.spi.Cache; import io.perbone.udao.spi.DataProviderException; import io.perbone.udao.spi.DataSource; import io.perbone.udao.spi.internal.AbstractDataSource; import io.perbone.udao.spi.internal.SimpleCursor; import io.perbone.udao.transaction.Transaction; import io.perbone.udao.transaction.TransactionException; import io.perbone.udao.util.ElementInfo; import io.perbone.udao.util.EntityUtils; import io.perbone.udao.util.StorableInfo; /** * Concrete implementation of {@link DataSource} for JDBC storage. * * @author Paulo Perbone <[email protected]> * @since 0.1.0 */ @SuppressWarnings("unchecked") public class JdbcDataSourceImpl extends AbstractDataSource { private static final String SQL_SELECT_COUNT = "SELECT COUNT(1) FROM %s"; private static final String SQL_SELECT_ALL = "SELECT * FROM %s ORDER BY %s"; private static final String SQL_SELECT_ONE = "SELECT * FROM %s WHERE %s"; // private static final String SQL_SELECT_EXISTS = "SELECT 1 FROM %s WHERE %s"; private static final String SQL_SELECT_BY_EXAMPLE = "SELECT * FROM %s WHERE %s ORDER BY %s"; private static final String SQL_INSERT = "INSERT INTO %s (%s) VALUES (%s)"; private static final String SQL_UPDATE = "UPDATE %s SET %s WHERE %s"; private static final String SQL_DELETE = "DELETE FROM %s WHERE %s"; private static final String DEFAULT_TARGET_NAME = "sql"; private final JdbcDataProviderImpl provider; private final SqlDialect dialect; private final Long fetchSize; private final Long queryTimeout; public JdbcDataSourceImpl(final JdbcDataProviderImpl provider, final SqlDialect dialect, final Long fetchSize, final Long queryTimeout) { super(); this.provider = provider; this.dialect = dialect; this.fetchSize = fetchSize; this.queryTimeout = queryTimeout; } @Override public boolean accepts(final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.accepts(type); } @Override public <T> T create(final Transaction txn, final Cache cache, final T bean) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.contains(bean)) throw new KeyViolationException(MESSAGE_KEY_VIOLATION); final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String columns = null; String placehoders = null; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { columns = (columns == null ? parseColumnName(einfo) : columns + "," + parseColumnName(einfo)); placehoders = (placehoders == null ? "?" : placehoders + ",?"); } } // FIXME sql statement string should be cached final String sql = String.format(SQL_INSERT, tableName, columns, placehoders); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } pst.executeUpdate(); pst.close(); commit(txn, conn); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'create' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } // FIXME handle all exceptions otherwise the transaction state can become out of sync finally { close(txn, conn); } /* Caches it */ cacheIt(txn, cache, bean); return bean; } @Override public <T> T create(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.create(txn, cache, bean, ttl, unit); } @Override public <T> List<T> create(final Transaction txn, final Cache cache, final List<T> beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { for (T bean : beans) { if (cache.contains(bean)) throw new KeyViolationException(MESSAGE_FOREIGN_KEY_VIOLATION); } final Class<?> type = beans.get(0).getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String columns = null; String placehoders = null; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { columns = (columns == null ? parseColumnName(einfo) : columns + "," + parseColumnName(einfo)); placehoders = (placehoders == null ? "?" : placehoders + ",?"); } } // FIXME sql statement string should be cached final String sql = String.format(SQL_INSERT, tableName, columns, placehoders); Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); for (T bean : beans) { int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } pst.addBatch(); } pst.executeBatch(); pst.close(); commit(txn, conn); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'create' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } /* Caches it */ for (T bean : beans) cacheIt(txn, cache, bean); return beans; } @Override public <T> List<T> create(final Transaction txn, final Cache cache, final List<T> beans, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.create(txn, cache, beans, ttl, unit); } @Override public <T> T save(final Transaction txn, final Cache cache, final T bean) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, bean); } @Override public <T> T save(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, bean, ttl, unit); } @Override public <T> List<T> save(final Transaction txn, final Cache cache, final List<T> beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, beans); } @Override public <T> List<T> save(final Transaction txn, final Cache cache, final List<T> beans, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, beans, ttl, unit); } @Override public <T> T fetchI(final Transaction txn, final Cache cache, final Class<T> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { T bean = cache.getI(id); if (bean != null) return bean; final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Where column value pst.setObject(1, id); final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The surrogate key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchI' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public <T> List<T> fetchI(final Transaction txn, final Cache cache, final Class<T> type, final Object... ids) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.fetchI(txn, cache, type, ids); } @Override public <T> T fetchP(final Transaction txn, final Cache cache, final Class<T> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); T bean = cache.getP(keys); if (bean != null) return bean; final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Long && sinfo.primaryKey().get(i).dataType() == DataType.DATE) { final Date dt = new Date((Long) value); pst.setObject(parameterIndex++, dt); } else if (value instanceof Date && sinfo.primaryKey().get(i).dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && sinfo.primaryKey().get(i).dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The primary key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchP' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T fetchA(final Transaction txn, final Cache cache, final Class<T> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); T bean = cache.getA(name, keys); if (bean != null) return bean; final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String where = ""; for (final ElementInfo einfo : sinfo.alternateKey(name)) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Long && sinfo.alternateKey(name).get(i).dataType() == DataType.DATE) { final Date dt = new Date((Long) value); pst.setObject(parameterIndex++, dt); } else if (value instanceof Date && sinfo.alternateKey(name).get(i).dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && sinfo.alternateKey(name).get(i).dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The alternate key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchA' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public boolean containsI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsI(id)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchI(txn, cache, type, id); } catch (final NotFoundException e) { return false; } return true; } @Override public boolean containsP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsP(keys)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchP(txn, cache, type, keys); } catch (final NotFoundException e) { return false; } return true; } @Override public boolean containsA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsA(name, keys)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchA(txn, cache, type, name, keys); } catch (final NotFoundException e) { return false; } return true; } @Override public <T> T updateI(final Transaction txn, final Cache cache, final T bean, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value pst.setObject(parameterIndex++, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); cache.removeI(id); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateI(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateI(txn, cache, bean, ttl, unit, id); } @Override public <T> T updateP(final Transaction txn, final Cache cache, final T bean, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where columns values for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The primary key did not match any bean"); cache.removeP(keys); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateP' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateP(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateP(txn, cache, bean, ttl, unit, keys); } @Override public <T> T updateA(final Transaction txn, final Cache cache, final T bean, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { Class<?> type = bean.getClass(); StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.alternateKey(name)) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); Connection conn = getConnection(txn); try { PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); pst = null; commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The alternate key did not match any bean"); cache.removeA(name, keys); // Clears the cache for this bean } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateA' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateA(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateA(txn, cache, bean, ttl, unit, name, keys); } @Override public <T> T patchI(Transaction txn, final Cache cache, final T bean, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && EntityUtils.value(bean, einfo.name()) != null) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { // do nothing (patch behavior) } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value pst.setObject(parameterIndex++, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); cache.removeI(id); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T patchI(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchI(txn, cache, bean, ttl, unit, id); } @Override public <T> T patchP(final Transaction txn, final Cache cache, final T bean, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && EntityUtils.value(bean, einfo.name()) != null) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { // do nothing (patch behavior) } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where columns values for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The primary key did not match any bean"); cache.removeP(keys); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateP' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T patchP(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchP(txn, cache, bean, ttl, unit, keys); } @Override public <T> T patchA(final Transaction txn, final Cache cache, final T bean, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchA(txn, cache, bean, name, keys); } @Override public <T> T patchA(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final String name, Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchA(txn, cache, bean, ttl, unit, name, keys); } @Override public void touchI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchI(txn, cache, type, id); } @Override public void touchI(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchI(txn, cache, type, ttl, unit, id); } @Override public void touchP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchP(txn, cache, type, keys); } @Override public void touchP(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchP(txn, cache, type, ttl, unit, keys); } @Override public void touchA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchA(txn, cache, type, name, keys); } @Override public void touchA(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchA(txn, cache, type, ttl, unit, name, keys); } @Override public void deleteI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_DELETE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Where column value pst.setObject(1, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'deleteI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_FOREIGN_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } /* Deletes from cache */ cache.deleteI(id); } @Override public void deleteP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.deleteP(txn, cache, type, keys); } @Override public void deleteA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.deleteA(txn, cache, type, name, keys); } @Override public void deleteX(final Transaction txn, final Cache cache, final Class<?> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final Map<String, List<Object>> whereValues = parseWhereValuesByExample(type, beans); final String where = parseWhereStatement(whereValues); // FIXME sql statement string should be cached final String sql = String.format(SQL_DELETE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (List<Object> values : whereValues.values()) { for (Object value : values) { if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate keys did not match any bean"); /* Delete from cache */ cache.invalidate(); // FIXME do not invalidate all cache for the bean type } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'deleteX' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_FOREIGN_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } } @Override public <T> T removeI(final Transaction txn, final Cache cache, final Class<T> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeI(txn, cache, type, id); } @Override public <T> T removeP(final Transaction txn, final Cache cache, final Class<T> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeP(txn, cache, type, keys); } @Override public <T> T removeA(final Transaction txn, final Cache cache, final Class<T> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeA(txn, cache, type, name, keys); } @Override public <T> Cursor<T> cursorI(final Transaction txn, final Cache cache, final Class<T> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String orderBy = parseColumnName(sinfo.surrogateKey()); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ALL, tableName, orderBy); return openCursor(txn, cache, type, sql); } @Override public <T> Cursor<T> cursorP(final Transaction txn, final Cache cache, final Class<T> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorP(txn, cache, type); } @Override public <T> Cursor<T> cursorA(final Transaction txn, final Cache cache, final Class<T> type, final String name) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorA(txn, cache, type, name); } @Override public <T> Cursor<T> cursorX(final Transaction txn, final Cache cache, final Class<T> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final Map<String, List<Object>> whereValues = parseWhereValuesByExample(type, beans); final String where = parseWhereStatement(whereValues); final String orderBy = parseOrderByStatement(sinfo); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_BY_EXAMPLE, tableName, where, orderBy); final List<Object> values = new ArrayList<Object>(); for (List<Object> wvalues : whereValues.values()) { for (Object value : wvalues) values.add(value); } return openCursor(txn, cache, type, sql, values); } @Override public <T> Cursor<T> cursorQ(final Transaction txn, final Cache cache, final Class<T> type, final Query query) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { checkDialectSupport(DERBY, MYSQL, ORACLE, POSTGRESQL); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseQueryWhere(type, query); final String limit = parseQueryLimit(query); final String order = parseQueryOrder(type, query); // FIXME sql statement string should be cached final String sql = parseQuerySelect("SELECT * FROM " + tableName, where, order, limit); return openCursor(txn, cache, type, sql); } @Override public <T> Cursor<T> cursorN(final Transaction txn, final Cache cache, final Class<T> type, final String nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorN(txn, cache, type, nquery); } @Override public <T> Cursor<T> cursorN(final Transaction txn, final Cache cache, final Class<T> type, final NativeQuery<T> nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorN(txn, cache, type, nquery); } @Override public long count(final Transaction txn, final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_COUNT, tableName); long count = -1; Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); final ResultSet rs = pst.executeQuery(); if (rs.next()) count = rs.getLong(1); rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'count' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return count; } @Override public long countX(final Transaction txn, final Cache cache, final Class<?> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countX(txn, cache, type, beans); } @Override public long countQ(final Transaction txn, final Cache cache, final Class<?> type, final Query query) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countQ(txn, cache, type, query); } @Override public long countN(final Transaction txn, final Cache cache, Class<?> type, final String nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countN(txn, cache, type, nquery); } @Override public long countN(final Transaction txn, final Cache cache, final Class<?> type, final NativeQuery<?> nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countN(txn, cache, type, nquery); } @Override public void expires(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.expires(cache, type); } @Override public void expires(final Cache cache, final Class<?> type, final Object criteria) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.expires(cache, type, criteria); } @Override public void invalidate(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { cache.invalidate(); } @Override public long prune(final Cache cache, final Class<?> type, final Object criteria) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.prune(cache, type, criteria); } @Override public void clear(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.clear(cache, type); } @Override public void evict() throws UnsupportedOperationException, IllegalStateException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.evict(); } @Override protected void onOpen() throws IllegalStateException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // do nothing } @Override protected void onClose() throws DataProviderException { // do nothing } /** * Checks for the given set of dialects with they are supported by this implementation. * * @param dialects * the set of supported dialects * * @throws UnsupportedOperationException * if the dialect is not supported */ private void checkDialectSupport(final SqlDialect... dialects) throws UnsupportedOperationException { boolean supported = false; for (SqlDialect d : dialects) if (d == dialect) supported = true; if (!supported) throw new UnsupportedOperationException( String.format("This method call is not yet supported for %s dialect", dialect)); } /** * Parses the where statement. * * @param whereValues * the columns and values for the where clause * * @return the where statement with value place holders */ private String parseWhereStatement(final Map<String, List<Object>> whereValues) { String where = ""; for (final String name : whereValues.keySet()) { boolean useInOperator = false; // Optimisation for IN clauses as it is much more expensive for the DBMS than an '=' if (whereValues.get(name).size() > 1) useInOperator = true; if (StringValidations.isValid(where)) where += " AND " + name + (useInOperator ? " IN (" : " = "); else where = name + (useInOperator ? " IN (" : " = "); for (int i = 0; i < whereValues.get(name).size(); i++) { if (useInOperator) { boolean first = !"?".equals(where.substring(where.length() - 1)); if (first) where += "?"; else where += ",?"; } else { where += "?"; } } if (useInOperator) where += ")"; } return where; } /** * Parses the natural order for the bean type. * <p> * It'll try surrogate key first and them primary key. * * @param sinfo * the bean storable info object * * @return a SQL string with all the collumn names for use with the ORDER BY command */ private String parseOrderByStatement(final StorableInfo sinfo) { String orderBy = ""; final List<ElementInfo> elements = new ArrayList<ElementInfo>(); if (sinfo.surrogateKey() != null) elements.add(sinfo.surrogateKey()); else for (final ElementInfo einfo : sinfo.primaryKey()) elements.add(einfo); for (final ElementInfo einfo : elements) { if (StringValidations.isValid(orderBy)) orderBy = orderBy + ", "; orderBy = orderBy + parseColumnName(einfo); } return orderBy; } /** * Parses the values for the where clause. * * @param type * the bean type * @param beans * sample beans to use as example * * @return the where values */ private Map<String, List<Object>> parseWhereValuesByExample(final Class<?> type, final Object... beans) { final Map<String, List<Object>> result = new Hashtable<String, List<Object>>(); final StorableInfo sinfo = EntityUtils.info(type); for (final Object bean : beans) { for (final ElementInfo einfo : sinfo.nonVirtualElements()) { final String name = einfo.firstAliasForTarget(DEFAULT_TARGET_NAME); final Object value = EntityUtils.value(bean, einfo.name()); if (value != null) { if (result.containsKey(name)) result.get(name).add(value); else { List<Object> colValues = new ArrayList<Object>(); colValues.add(value); result.put(name, colValues); } } } } return result; } /** * Parses the table name for the entity type. * <p> * It will try for the target alias first and if not present it will use the type name as the * table name. * * @param sinfo * the {@link StorableInfo} for the bean type * * @return the table name */ // private String parseTableName(final StorableInfo sinfo) // { // assert (sinfo != null); // // String schema = sinfo.schema(); // String name = sinfo.firstAliasForTarget(DEFAULT_TARGET_NAME); // // if (name == null) // name = sinfo.name(); // // return schema == null ? name.toLowerCase() : schema.toLowerCase() + "." + name.toLowerCase(); // } /** * Parses the column name for the given {@link ElementInfo}. * <p> * It will try for the target alias first and if not present it will use the element name as the * column name. * * @param einfo * the {@link ElementInfo} * * @return the column name */ private String parseColumnName(final ElementInfo einfo) { String columnName = einfo.firstAliasForTarget(DEFAULT_TARGET_NAME); if (columnName == null) return columnName = einfo.name(); return columnName.toUpperCase(); } /** * * @param type * @param query * @return */ private String parseQueryWhere(final Class<?> type, final Query query) { if (!query.hasWhere()) return null; String where = "WHERE "; ElementInfo einfo; for (Expression exp : query.where()) { switch (exp.type()) { case EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<>" : "=", toJdbcValue(einfo, exp.value())); break; case LESS: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? ">=" : "<", toJdbcValue(einfo, exp.value())); break; case LESS_EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? ">" : "<=", toJdbcValue(einfo, exp.value())); break; case GREATER: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<=" : ">", toJdbcValue(einfo, exp.value())); break; case GREATER_EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<" : ">=", toJdbcValue(einfo, exp.value())); break; case IN: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s (%s)", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "NOT IN" : "IN", toJdbcValues(einfo, exp.values())); break; case BETWEEN: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s %s AND %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "NOT BETWEEN" : "BETWEEN", toJdbcValues(einfo, exp.begin()), toJdbcValues(einfo, exp.end())); break; case IS_NULL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "IS NOT NULL" : "IS NULL"); break; case IS_NOT_NULL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "IS NULL" : "IS NOT NULL"); break; case AND: where += " AND "; break; case OR: where += " OR "; break; case OPEN_PARENTHESIS: where += "("; break; case CLOSE_PARENTHESIS: where += ")"; break; default: break; } } return where; } private String toJdbcValue(final ElementInfo einfo, final Object value) { if (value == null) return "null"; switch (einfo.dataType()) { case BOOLEAN: if (value instanceof Boolean) return (Boolean) value ? "true" : "false"; else if (value instanceof Integer) return ((Integer) value == 1) ? "1" : "0"; else if (value instanceof Long) return ((Long) value == 1) ? "1" : "0"; else if (value instanceof String) return "" + Boolean.parseBoolean((String) value); else return value.toString(); case BYTE: case BYTES: case LONG: case SHORT: case INT: case FLOAT: case DOUBLE: case ID: case REF: case TUPLE: return value.toString(); case CHAR: case STRING: case ENUM: return "'" + value.toString() + "'"; case DATE: if (dialect == POSTGRESQL) { if (value instanceof Date) // PostgreSQL to_timestamp has only seconds resolution return "to_timestamp(" + ((Date) value).getTime() / 1000 + ")"; else if (value instanceof Long) // PostgreSQL to_timestamp has only seconds resolution return "to_timestamp(" + ((Long) value) / 1000 + ")"; else return "{d '" + value.toString() + "'}"; } else return "{d '" + value.toString() + "'}"; case TIME: return "{t '" + value.toString() + "'}"; case TIMESTAMP: return "{ts '" + value.toString() + "'}"; case LIST: case UNKNOWN: return value.toString(); default: return value.toString(); } } private String toJdbcValues(final ElementInfo einfo, final Object... values) { String result = null; for (final Object value : values) { final String tmp = toJdbcValue(einfo, value); result = result == null ? tmp : result + ", " + tmp; } return result; } private String parseQueryLimit(final Query query) { if (!query.hasLimit()) return null; String limit = null; switch (dialect) { case ORACLE: limit = String.format(" ROWNUM < %d", query.limit()); break; case POSTGRESQL: limit = String.format(" LIMIT %d OFFSET %d", query.limit(), query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset() - 1) : 0L); break; case MYSQL: limit = String.format(" LIMIT %d,%d", query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset() - 1) : 0L, query.limit()); break; case DERBY: limit = String.format(" OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", query.hasOffset() ? query.offset() : 0L, query.limit()); break; default: // do nothing } return limit; } private String parseQueryOrder(final Class<?> type, final Query query) { if (!query.hasOrder()) return null; String order = null; for (final Pair<String, Boolean> element : query.order()) { final String column = EntityUtils.info(type, element.first()).firstAliasForTarget(DEFAULT_TARGET_NAME); final String asc = element.second() ? "ASC" : "DESC"; if (order == null) order = String.format(" ORDER BY %s %s", column, asc); else order = String.format("%s, %s %s", order, column, asc); } return order; } private String parseQuerySelect(final String baseSelect, final String where, final String order, final String limit) { String sql = baseSelect; if (dialect == SqlDialect.ORACLE) sql = sql + (where == null ? "" : " " + where) + (order == null ? "" : " " + order) + (limit == null ? "" : " " + where == null ? "WHERE " + limit : limit); else sql = sql + (where == null ? "" : " " + where) + (order == null ? "" : " " + order) + (limit == null ? "" : " " + limit); return sql; } private <T> Cursor<T> openCursor(final Transaction txn, final Cache cache, final Class<T> type, final String sql) throws OperationTimeoutException, DataProviderException { return openCursor(txn, cache, type, sql, Collections.emptyList()); } private <T> Cursor<T> openCursor(final Transaction txn, final Cache cache, final Class<T> type, final String sql, List<Object> values) throws OperationTimeoutException, DataProviderException { Cursor<T> cursor = null; final Connection conn = getConnection(txn); try { final List<T> lrs = new ArrayList<T>(); final PreparedStatement pst = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); pst.setFetchSize(fetchSize.intValue()); setQueryTimeout(pst); if (!values.isEmpty()) { int parameterIndex = 1; for (final Object value : values) { if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else { pst.setObject(parameterIndex++, value); } } } final ResultSet rs = pst.executeQuery(); while (rs.next()) { final T bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean lrs.add(bean); // Adds to the cursor collection } rs.close(); T[] resultSet = (T[]) Array.newInstance(type, lrs.size()); System.arraycopy(lrs.toArray(), 0, resultSet, 0, lrs.size()); lrs.clear(); cursor = new SimpleCursor<T>(resultSet); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'cursor*' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return cursor; } /** * Assembles a new entity object based on the content of the current result set position. * * @param type * @param rs * * @return * * @throws IllegalArgumentException * @throws SQLException */ @SuppressWarnings("rawtypes") private <T> T makeEntity(final Class<T> type, final ResultSet rs) throws IllegalArgumentException, SQLException { T bean = null; final ResultSetMetaData meta = rs.getMetaData(); try { bean = type.newInstance(); } catch (final InstantiationException e) { return null; } catch (final IllegalAccessException e) { return null; } // FIXME support for all SQL/Java types for (int i = 1; i <= meta.getColumnCount(); i++) { final Object value = rs.getObject(i); if (rs.wasNull()) continue; final String colName = meta.getColumnName(i); final ElementInfo einfo = EntityUtils.info(bean.getClass(), colName); if (einfo == null) continue; final Class<?> beanFieldType = einfo.type(); if (beanFieldType.equals(TimeUnit.class)) { EntityUtils.value(bean, colName, EntityUtils.parseTimeUnit((String) value)); } else if (beanFieldType.isEnum()) { EntityUtils.value(bean, colName, Enum.valueOf((Class<Enum>) beanFieldType, (String) value)); } // else if (value instanceof Date) // { // BeanUtils.value(bean, colName, ((Date) value).getTime()); // } // else if (value instanceof Timestamp) // { // BeanUtils.value(bean, colName, ((Timestamp) value).getTime()); // } else if (value instanceof Integer) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, value); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, new Long(((Integer) value))); else if (beanFieldType.equals(Boolean.class)) EntityUtils.value(bean, colName, ((Integer) value) == 1 ? true : false); else EntityUtils.value(bean, colName, value); } else if (value instanceof Long) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, ((Long) value).intValue()); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, value); else EntityUtils.value(bean, colName, value); } else if (value instanceof BigDecimal) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, ((BigDecimal) value).intValue()); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, ((BigDecimal) value).longValue()); else EntityUtils.value(bean, colName, value); } else { EntityUtils.value(bean, colName, value); } } return bean; } /** * Caches the given bean into the given cache only if there is no current transaction in * progress. * * @param cache * the cache instance * @param eban * the bean to be cached */ private void cacheIt(final Transaction txn, final Cache cache, final Object bean) { if (!transactionInProgress(txn)) cache.add(bean); // Save to cache it } /** * Retrieves the connection from the current transaction. If there is no transaction, try to * acquire a transaction from the providers pool. * * @param txn * the current transaction object; can be {@code null} with there is no transaction * * @return the connection * * @throws NotEnoughResourceException * if a database access error occurs */ private Connection getConnection(final Transaction txn) throws NotEnoughResourceException { return txn == null ? provider.getConnection() : ((JdbcTransactionImpl) txn).getConnection(); } /** * Sets the query timeout to the given Statement object. * * @param st * the Statement object to set * * @throws SQLException * if a database access error occurs * @throws SQLException * if this method is called on a closed Statement * @throws SQLException * if the condition seconds >= 0 is not satisfied */ private void setQueryTimeout(final Statement st) throws SQLException { if (queryTimeout > 0L) { st.setQueryTimeout(queryTimeout.intValue()); } } /** * Commits the given connection. If the connection is participating in a transaction this call * has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to commit * * @throws SQLException * if a database access error occurs */ private void commit(final Transaction txn, final Connection conn) throws SQLException { if (txn == null) { conn.commit(); } } /** * Roll backs the given connection. If the connection is participating in a transaction this * call has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to roll back * * @throws SQLException * if a database access error occurs */ private void rollback(final Transaction txn, final Connection conn) throws SQLException { if (txn == null) { conn.rollback(); } } /** * Closes the given connection. If the connection is participating in a transaction this call * has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to close * * @throws DataProviderException * if a database access error occurs */ private void close(final Transaction txn, final Connection conn) throws DataProviderException { if (txn == null) { try { conn.close(); } catch (final SQLException e) { throw new DataProviderException("Could not close the database connection", e); } } } }
udao-provider-jdbc/src/main/java/io/perbone/udao/provider/jdbc/JdbcDataSourceImpl.java
/* * This file is part of UDAO * https://github.com/perbone/udao/ * * Copyright 2013-2017 Paulo Perbone * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package io.perbone.udao.provider.jdbc; import static io.perbone.udao.provider.jdbc.SqlDialect.DERBY; import static io.perbone.udao.provider.jdbc.SqlDialect.MYSQL; import static io.perbone.udao.provider.jdbc.SqlDialect.ORACLE; import static io.perbone.udao.provider.jdbc.SqlDialect.POSTGRESQL; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import io.perbone.toolbox.collection.Pair; import io.perbone.toolbox.provider.NotEnoughResourceException; import io.perbone.toolbox.provider.OperationTimeoutException; import io.perbone.toolbox.validation.StringValidations; import io.perbone.udao.Cursor; import io.perbone.udao.DataConstraintViolationException; import io.perbone.udao.KeyViolationException; import io.perbone.udao.NotFoundException; import io.perbone.udao.annotation.DataType; import io.perbone.udao.query.Expression; import io.perbone.udao.query.NativeQuery; import io.perbone.udao.query.Query; import io.perbone.udao.spi.Cache; import io.perbone.udao.spi.DataProviderException; import io.perbone.udao.spi.DataSource; import io.perbone.udao.spi.internal.AbstractDataSource; import io.perbone.udao.spi.internal.SimpleCursor; import io.perbone.udao.transaction.Transaction; import io.perbone.udao.transaction.TransactionException; import io.perbone.udao.util.ElementInfo; import io.perbone.udao.util.EntityUtils; import io.perbone.udao.util.StorableInfo; /** * Concrete implementation of {@link DataSource} for JDBC storage. * * @author Paulo Perbone <[email protected]> * @since 0.1.0 */ @SuppressWarnings("unchecked") public class JdbcDataSourceImpl extends AbstractDataSource { private static final String SQL_SELECT_COUNT = "SELECT COUNT(1) FROM %s"; private static final String SQL_SELECT_ALL = "SELECT * FROM %s ORDER BY %s"; private static final String SQL_SELECT_ONE = "SELECT * FROM %s WHERE %s"; // private static final String SQL_SELECT_EXISTS = "SELECT 1 FROM %s WHERE %s"; private static final String SQL_SELECT_BY_EXAMPLE = "SELECT * FROM %s WHERE %s ORDER BY %s"; private static final String SQL_INSERT = "INSERT INTO %s (%s) VALUES (%s)"; private static final String SQL_UPDATE = "UPDATE %s SET %s WHERE %s"; private static final String SQL_DELETE = "DELETE FROM %s WHERE %s"; private static final String DEFAULT_TARGET_NAME = "sql"; private final JdbcDataProviderImpl provider; private final SqlDialect dialect; private final Long fetchSize; private final Long queryTimeout; public JdbcDataSourceImpl(final JdbcDataProviderImpl provider, final SqlDialect dialect, final Long fetchSize, final Long queryTimeout) { super(); this.provider = provider; this.dialect = dialect; this.fetchSize = fetchSize; this.queryTimeout = queryTimeout; } @Override public boolean accepts(final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.accepts(type); } @Override public <T> T create(final Transaction txn, final Cache cache, final T bean) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.contains(bean)) throw new KeyViolationException(MESSAGE_KEY_VIOLATION); final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String columns = null; String placehoders = null; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { columns = (columns == null ? parseColumnName(einfo) : columns + "," + parseColumnName(einfo)); placehoders = (placehoders == null ? "?" : placehoders + ",?"); } } // FIXME sql statement string should be cached final String sql = String.format(SQL_INSERT, tableName, columns, placehoders); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } pst.executeUpdate(); pst.close(); commit(txn, conn); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'create' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } // FIXME handle all exceptions otherwise the transaction state can become out of sync finally { close(txn, conn); } /* Caches it */ cacheIt(txn, cache, bean); return bean; } @Override public <T> T create(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.create(txn, cache, bean, ttl, unit); } @Override public <T> List<T> create(final Transaction txn, final Cache cache, final List<T> beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { for (T bean : beans) { if (cache.contains(bean)) throw new KeyViolationException(MESSAGE_FOREIGN_KEY_VIOLATION); } final Class<?> type = beans.get(0).getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String columns = null; String placehoders = null; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { columns = (columns == null ? parseColumnName(einfo) : columns + "," + parseColumnName(einfo)); placehoders = (placehoders == null ? "?" : placehoders + ",?"); } } // FIXME sql statement string should be cached final String sql = String.format(SQL_INSERT, tableName, columns, placehoders); Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); for (T bean : beans) { int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } pst.addBatch(); } pst.executeBatch(); pst.close(); commit(txn, conn); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'create' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } /* Caches it */ for (T bean : beans) cacheIt(txn, cache, bean); return beans; } @Override public <T> List<T> create(final Transaction txn, final Cache cache, final List<T> beans, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.create(txn, cache, beans, ttl, unit); } @Override public <T> T save(final Transaction txn, final Cache cache, final T bean) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, bean); } @Override public <T> T save(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, bean, ttl, unit); } @Override public <T> List<T> save(final Transaction txn, final Cache cache, final List<T> beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, beans); } @Override public <T> List<T> save(final Transaction txn, final Cache cache, final List<T> beans, final long ttl, final TimeUnit unit) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.save(txn, cache, beans, ttl, unit); } @Override public <T> T fetchI(final Transaction txn, final Cache cache, final Class<T> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { T bean = cache.getI(id); if (bean != null) return bean; final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Where column value pst.setObject(1, id); final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The surrogate key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchI' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public <T> List<T> fetchI(final Transaction txn, final Cache cache, final Class<T> type, final Object... ids) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.fetchI(txn, cache, type, ids); } @Override public <T> T fetchP(final Transaction txn, final Cache cache, final Class<T> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); T bean = cache.getP(keys); if (bean != null) return bean; final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Long && sinfo.primaryKey().get(i).dataType() == DataType.DATE) { final Date dt = new Date((Long) value); pst.setObject(parameterIndex++, dt); } else if (value instanceof Date && sinfo.primaryKey().get(i).dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && sinfo.primaryKey().get(i).dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The primary key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchP' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T fetchA(final Transaction txn, final Cache cache, final Class<T> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); T bean = cache.getA(name, keys); if (bean != null) return bean; final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String where = ""; for (final ElementInfo einfo : sinfo.alternateKey(name)) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ONE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Long && sinfo.alternateKey(name).get(i).dataType() == DataType.DATE) { final Date dt = new Date((Long) value); pst.setObject(parameterIndex++, dt); } else if (value instanceof Date && sinfo.alternateKey(name).get(i).dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && sinfo.alternateKey(name).get(i).dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } final ResultSet rs = pst.executeQuery(); if (!rs.next()) { rs.close(); pst.close(); throw new NotFoundException("The alternate key did not match any bean"); } bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'fetchA' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return bean; } @Override public boolean containsI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsI(id)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchI(txn, cache, type, id); } catch (final NotFoundException e) { return false; } return true; } @Override public boolean containsP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsP(keys)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchP(txn, cache, type, keys); } catch (final NotFoundException e) { return false; } return true; } @Override public boolean containsA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { if (cache.containsA(name, keys)) return true; // FIXME should use SQL_SELECT_EXISTS try { fetchA(txn, cache, type, name, keys); } catch (final NotFoundException e) { return false; } return true; } @Override public <T> T updateI(final Transaction txn, final Cache cache, final T bean, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value pst.setObject(parameterIndex++, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); cache.removeI(id); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateI(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateI(txn, cache, bean, ttl, unit, id); } @Override public <T> T updateP(final Transaction txn, final Cache cache, final T bean, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where columns values for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The primary key did not match any bean"); cache.removeP(keys); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateP' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateP(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateP(txn, cache, bean, ttl, unit, keys); } @Override public <T> T updateA(final Transaction txn, final Cache cache, final T bean, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { Class<?> type = bean.getClass(); StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.alternateKey(name)) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); Connection conn = getConnection(txn); try { PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && (!einfo.metadata() || (einfo.metadata() && EntityUtils.value(bean, einfo.name()) != null))) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { pst.setObject(parameterIndex++, value); } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); pst = null; commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The alternate key did not match any bean"); cache.removeA(name, keys); // Clears the cache for this bean } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateA' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T updateA(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.updateA(txn, cache, bean, ttl, unit, name, keys); } @Override public <T> T patchI(Transaction txn, final Cache cache, final T bean, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && EntityUtils.value(bean, einfo.name()) != null) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { // do nothing (patch behavior) } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where column value pst.setObject(parameterIndex++, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); cache.removeI(id); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T patchI(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchI(txn, cache, bean, ttl, unit, id); } @Override public <T> T patchP(final Transaction txn, final Cache cache, final T bean, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final Class<T> type = (Class<T>) bean.getClass(); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); String setColumns = ""; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual() && EntityUtils.value(bean, einfo.name()) != null) { if (StringValidations.isValid(setColumns)) setColumns = setColumns + ", "; setColumns = setColumns + parseColumnName(einfo) + "=?"; } } String where = ""; for (final ElementInfo einfo : sinfo.primaryKey()) { if (StringValidations.isValid(where)) where += " AND "; where = where + parseColumnName(einfo) + "=?"; } // FIXME sql statement string should be cached final String sql = String.format(SQL_UPDATE, tableName, setColumns, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Columns values int parameterIndex = 1; for (final ElementInfo einfo : sinfo.elements()) { if (!einfo.virtual()) { final Object value = EntityUtils.value(bean, einfo.name()); if (value == null) { // do nothing (patch behavior) } else if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else if (value instanceof Date && einfo.dataType() == DataType.DATE) { final Timestamp ts = new Timestamp(((Date) value).getTime()); pst.setTimestamp(parameterIndex++, ts); } else if (value instanceof Date && einfo.dataType() == DataType.LONG) { final Long tmp = ((Date) value).getTime(); pst.setLong(parameterIndex++, tmp); } else pst.setObject(parameterIndex++, value); } } // Where columns values for (int i = 0; i < keys.length; i++) { final Object value = keys[i]; if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The primary key did not match any bean"); cache.removeP(keys); // Clear this (potentially dirty) bean from cache } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'updateP' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { // FIXME support sql state 23502 (not null constraint fails) String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().equals("23502")) // NOT NULL FAIL throw new DataConstraintViolationException(msg, sqle); else if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } return bean; } @Override public <T> T patchP(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchP(txn, cache, bean, ttl, unit, keys); } @Override public <T> T patchA(final Transaction txn, final Cache cache, final T bean, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchA(txn, cache, bean, name, keys); } @Override public <T> T patchA(final Transaction txn, final Cache cache, final T bean, final long ttl, final TimeUnit unit, final String name, Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.patchA(txn, cache, bean, ttl, unit, name, keys); } @Override public void touchI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchI(txn, cache, type, id); } @Override public void touchI(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchI(txn, cache, type, ttl, unit, id); } @Override public void touchP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchP(txn, cache, type, keys); } @Override public void touchP(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchP(txn, cache, type, ttl, unit, keys); } @Override public void touchA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchA(txn, cache, type, name, keys); } @Override public void touchA(final Transaction txn, final Cache cache, final Class<?> type, final long ttl, final TimeUnit unit, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.touchA(txn, cache, type, ttl, unit, name, keys); } @Override public void deleteI(final Transaction txn, final Cache cache, final Class<?> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseColumnName(sinfo.surrogateKey()) + "=?"; // FIXME sql statement string should be cached final String sql = String.format(SQL_DELETE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); // Where column value pst.setObject(1, id); final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate key did not match any bean"); } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'deleteI' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_FOREIGN_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } /* Deletes from cache */ cache.deleteI(id); } @Override public void deleteP(final Transaction txn, final Cache cache, final Class<?> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.deleteP(txn, cache, type, keys); } @Override public void deleteA(final Transaction txn, final Cache cache, final Class<?> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.deleteA(txn, cache, type, name, keys); } @Override public void deleteX(final Transaction txn, final Cache cache, final Class<?> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final Map<String, List<Object>> whereValues = parseWhereValuesByExample(type, beans); final String where = parseWhereStatement(whereValues); // FIXME sql statement string should be cached final String sql = String.format(SQL_DELETE, tableName, where); final Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); int parameterIndex = 1; for (List<Object> values : whereValues.values()) { for (Object value : values) { if (value instanceof Enum<?>) pst.setObject(parameterIndex++, value.toString()); else pst.setObject(parameterIndex++, value); } } final int affectedRows = pst.executeUpdate(); pst.close(); commit(txn, conn); if (affectedRows == 0) throw new NotFoundException("The surrogate keys did not match any bean"); /* Delete from cache */ cache.invalidate(); // FIXME do not invalidate all cache for the bean type } catch (final SQLTimeoutException sqle) { String msg = "The currently executing 'deleteX' operation is timed out"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } throw new OperationTimeoutException(msg, sqle); } catch (final SQLException sqle) { String msg = sqle.getSQLState().startsWith("23") ? MESSAGE_FOREIGN_KEY_VIOLATION : "Could not execute the database statement"; try { rollback(txn, conn); } catch (final SQLException e) { msg = msg + " and could not roll back the transaction; there can be inconsistencies"; sqle.setNextException(e); } if (sqle.getSQLState().startsWith("23")) throw new KeyViolationException(msg, sqle); else throw new DataProviderException(msg, sqle); } finally { close(txn, conn); } } @Override public <T> T removeI(final Transaction txn, final Cache cache, final Class<T> type, final Object id) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeI(txn, cache, type, id); } @Override public <T> T removeP(final Transaction txn, final Cache cache, final Class<T> type, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeP(txn, cache, type, keys); } @Override public <T> T removeA(final Transaction txn, final Cache cache, final Class<T> type, final String name, final Object... keys) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, NotFoundException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.removeA(txn, cache, type, name, keys); } @Override public <T> Cursor<T> cursorI(final Transaction txn, final Cache cache, final Class<T> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String orderBy = parseColumnName(sinfo.surrogateKey()); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_ALL, tableName, orderBy); return openCursor(txn, cache, type, sql); } @Override public <T> Cursor<T> cursorP(final Transaction txn, final Cache cache, final Class<T> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorP(txn, cache, type); } @Override public <T> Cursor<T> cursorA(final Transaction txn, final Cache cache, final Class<T> type, final String name) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorA(txn, cache, type, name); } @Override public <T> Cursor<T> cursorX(final Transaction txn, final Cache cache, final Class<T> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final Map<String, List<Object>> whereValues = parseWhereValuesByExample(type, beans); final String where = parseWhereStatement(whereValues); final String orderBy = parseOrderByStatement(sinfo); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_BY_EXAMPLE, tableName, where, orderBy); final List<Object> values = new ArrayList<Object>(); for (List<Object> wvalues : whereValues.values()) { for (Object value : wvalues) values.add(value); } return openCursor(txn, cache, type, sql, values); } @Override public <T> Cursor<T> cursorQ(final Transaction txn, final Cache cache, final Class<T> type, final Query query) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { checkDialectSupport(DERBY, MYSQL, ORACLE, POSTGRESQL); final StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); final String where = parseQueryWhere(type, query); final String limit = parseQueryLimit(query); final String order = parseQueryOrder(type, query); // FIXME sql statement string should be cached final String sql = parseQuerySelect("SELECT * FROM " + tableName, where, order, limit); return openCursor(txn, cache, type, sql); } @Override public <T> Cursor<T> cursorN(final Transaction txn, final Cache cache, final Class<T> type, final String nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorN(txn, cache, type, nquery); } @Override public <T> Cursor<T> cursorN(final Transaction txn, final Cache cache, final Class<T> type, final NativeQuery<T> nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.cursorN(txn, cache, type, nquery); } @Override public long count(final Transaction txn, final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { StorableInfo sinfo = EntityUtils.info(type); final String tableName = parseTableName(DEFAULT_TARGET_NAME, sinfo); // FIXME sql statement string should be cached final String sql = String.format(SQL_SELECT_COUNT, tableName); long count = -1; Connection conn = getConnection(txn); try { final PreparedStatement pst = conn.prepareStatement(sql); setQueryTimeout(pst); final ResultSet rs = pst.executeQuery(); if (rs.next()) count = rs.getLong(1); rs.close(); pst.close(); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'count' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return count; } @Override public long countX(final Transaction txn, final Cache cache, final Class<?> type, final Object... beans) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countX(txn, cache, type, beans); } @Override public long countQ(final Transaction txn, final Cache cache, final Class<?> type, final Query query) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countQ(txn, cache, type, query); } @Override public long countN(final Transaction txn, final Cache cache, Class<?> type, final String nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countN(txn, cache, type, nquery); } @Override public long countN(final Transaction txn, final Cache cache, final Class<?> type, final NativeQuery<?> nquery) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, TransactionException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.countN(txn, cache, type, nquery); } @Override public void expires(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.expires(cache, type); } @Override public void expires(final Cache cache, final Class<?> type, final Object criteria) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.expires(cache, type, criteria); } @Override public void invalidate(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { cache.invalidate(); } @Override public long prune(final Cache cache, final Class<?> type, final Object criteria) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub return super.prune(cache, type, criteria); } @Override public void clear(final Cache cache, final Class<?> type) throws UnsupportedOperationException, IllegalStateException, IllegalArgumentException, KeyViolationException, DataConstraintViolationException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.clear(cache, type); } @Override public void evict() throws UnsupportedOperationException, IllegalStateException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // TODO Auto-generated method stub super.evict(); } @Override protected void onOpen() throws IllegalStateException, OperationTimeoutException, NotEnoughResourceException, DataProviderException { // do nothing } @Override protected void onClose() throws DataProviderException { // do nothing } /** * Checks for the given set of dialects with they are supported by this implementation. * * @param dialects * the set of supported dialects * * @throws UnsupportedOperationException * if the dialect is not supported */ private void checkDialectSupport(final SqlDialect... dialects) throws UnsupportedOperationException { boolean supported = false; for (SqlDialect d : dialects) if (d == dialect) supported = true; if (!supported) throw new UnsupportedOperationException( String.format("This method call is not yet supported for %s dialect", dialect)); } /** * Parses the where statement. * * @param whereValues * the columns and values for the where clause * * @return the where statement with value place holders */ private String parseWhereStatement(final Map<String, List<Object>> whereValues) { String where = ""; for (final String name : whereValues.keySet()) { boolean useInOperator = false; // Optimisation for IN clauses as it is much more expensive for the DBMS than an '=' if (whereValues.get(name).size() > 1) useInOperator = true; if (StringValidations.isValid(where)) where += " AND " + name + (useInOperator ? " IN (" : " = "); else where = name + (useInOperator ? " IN (" : " = "); for (int i = 0; i < whereValues.get(name).size(); i++) { if (useInOperator) { boolean first = !"?".equals(where.substring(where.length() - 1)); if (first) where += "?"; else where += ",?"; } else { where += "?"; } } if (useInOperator) where += ")"; } return where; } /** * Parses the natural order for the bean type. * <p> * It'll try surrogate key first and them primary key. * * @param sinfo * the bean storable info object * * @return a SQL string with all the collumn names for use with the ORDER BY command */ private String parseOrderByStatement(final StorableInfo sinfo) { String orderBy = ""; final List<ElementInfo> elements = new ArrayList<ElementInfo>(); if (sinfo.surrogateKey() != null) elements.add(sinfo.surrogateKey()); else for (final ElementInfo einfo : sinfo.primaryKey()) elements.add(einfo); for (final ElementInfo einfo : elements) { if (StringValidations.isValid(orderBy)) orderBy = orderBy + ", "; orderBy = orderBy + parseColumnName(einfo); } return orderBy; } /** * Parses the values for the where clause. * * @param type * the bean type * @param beans * sample beans to use as example * * @return the where values */ private Map<String, List<Object>> parseWhereValuesByExample(final Class<?> type, final Object... beans) { final Map<String, List<Object>> result = new Hashtable<String, List<Object>>(); final StorableInfo sinfo = EntityUtils.info(type); for (final Object bean : beans) { for (final ElementInfo einfo : sinfo.nonVirtualElements()) { final String name = einfo.firstAliasForTarget(DEFAULT_TARGET_NAME); final Object value = EntityUtils.value(bean, einfo.name()); if (value != null) { if (result.containsKey(name)) result.get(name).add(value); else { List<Object> colValues = new ArrayList<Object>(); colValues.add(value); result.put(name, colValues); } } } } return result; } /** * Parses the table name for the entity type. * <p> * It will try for the target alias first and if not present it will use the type name as the * table name. * * @param sinfo * the {@link StorableInfo} for the bean type * * @return the table name */ // private String parseTableName(final StorableInfo sinfo) // { // assert (sinfo != null); // // String schema = sinfo.schema(); // String name = sinfo.firstAliasForTarget(DEFAULT_TARGET_NAME); // // if (name == null) // name = sinfo.name(); // // return schema == null ? name.toLowerCase() : schema.toLowerCase() + "." + name.toLowerCase(); // } /** * Parses the column name for the given {@link ElementInfo}. * <p> * It will try for the target alias first and if not present it will use the element name as the * column name. * * @param einfo * the {@link ElementInfo} * * @return the column name */ private String parseColumnName(final ElementInfo einfo) { String columnName = einfo.firstAliasForTarget(DEFAULT_TARGET_NAME); if (columnName == null) return columnName = einfo.name(); return columnName.toUpperCase(); } /** * * @param type * @param query * @return */ private String parseQueryWhere(final Class<?> type, final Query query) { if (!query.hasWhere()) return null; String where = "WHERE "; ElementInfo einfo; for (Expression exp : query.where()) { switch (exp.type()) { case EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<>" : "=", toJdbcValue(einfo, exp.value())); break; case LESS: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? ">=" : "<", toJdbcValue(einfo, exp.value())); break; case LESS_EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? ">" : "<=", toJdbcValue(einfo, exp.value())); break; case GREATER: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<=" : ">", toJdbcValue(einfo, exp.value())); break; case GREATER_EQUAL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s%s%s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "<" : ">=", toJdbcValue(einfo, exp.value())); break; case IN: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s (%s)", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "NOT IN" : "IN", toJdbcValues(einfo, exp.values())); break; case BETWEEN: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s %s AND %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "NOT BETWEEN" : "BETWEEN", toJdbcValues(einfo, exp.begin()), toJdbcValues(einfo, exp.end())); break; case IS_NULL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "IS NOT NULL" : "IS NULL"); break; case IS_NOT_NULL: einfo = EntityUtils.info(type, exp.name()); where += String.format("%s %s", einfo.firstAliasForTarget(DEFAULT_TARGET_NAME), exp.not() ? "IS NULL" : "IS NOT NULL"); break; case AND: where += " AND "; break; case OR: where += " OR "; break; case OPEN_PARENTHESIS: where += "("; break; case CLOSE_PARENTHESIS: where += ")"; break; default: break; } } return where; } private String toJdbcValue(final ElementInfo einfo, final Object value) { if (value == null) return "null"; switch (einfo.dataType()) { case BOOLEAN: if (value instanceof Boolean) return (Boolean) value ? "true" : "false"; else if (value instanceof Integer) return ((Integer) value == 1) ? "1" : "0"; else if (value instanceof Long) return ((Long) value == 1) ? "1" : "0"; else if (value instanceof String) return "" + Boolean.parseBoolean((String) value); else return value.toString(); case BYTE: case BYTES: case LONG: case SHORT: case INT: case FLOAT: case DOUBLE: case ID: case REF: case TUPLE: return value.toString(); case CHAR: case STRING: case ENUM: return "'" + value.toString() + "'"; case DATE: if (dialect == POSTGRESQL) { if (value instanceof Date) // PostgreSQL to_timestamp has only seconds resolution return "to_timestamp(" + ((Date) value).getTime() / 1000 + ")"; else if (value instanceof Long) // PostgreSQL to_timestamp has only seconds resolution return "to_timestamp(" + ((Long) value) / 1000 + ")"; else return "{d '" + value.toString() + "'}"; } else return "{d '" + value.toString() + "'}"; case TIME: return "{t '" + value.toString() + "'}"; case TIMESTAMP: return "{ts '" + value.toString() + "'}"; case LIST: case UNKNOWN: return value.toString(); default: return value.toString(); } } private String toJdbcValues(final ElementInfo einfo, final Object... values) { String result = null; for (final Object value : values) { final String tmp = toJdbcValue(einfo, value); result = result == null ? tmp : result + ", " + tmp; } return result; } private String parseQueryLimit(final Query query) { if (!query.hasLimit()) return null; String limit = null; switch (dialect) { case ORACLE: limit = String.format(" ROWNUM < %d", query.limit()); break; case POSTGRESQL: limit = String.format(" LIMIT %d OFFSET %d", query.limit(), query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset() - 1) : 0L); break; case MYSQL: limit = String.format(" LIMIT %d,%d", query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset()) : 0L, query.limit()); break; case DERBY: limit = String.format(" OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", query.hasOffset() ? query.offset() : 0L, query.limit()); break; default: // do nothing } return limit; } private String parseQueryOrder(final Class<?> type, final Query query) { if (!query.hasOrder()) return null; String order = null; for (final Pair<String, Boolean> element : query.order()) { final String column = EntityUtils.info(type, element.first()).firstAliasForTarget(DEFAULT_TARGET_NAME); final String asc = element.second() ? "ASC" : "DESC"; if (order == null) order = String.format(" ORDER BY %s %s", column, asc); else order = String.format("%s, %s %s", order, column, asc); } return order; } private String parseQuerySelect(final String baseSelect, final String where, final String order, final String limit) { String sql = baseSelect; if (dialect == SqlDialect.ORACLE) sql = sql + (where == null ? "" : " " + where) + (order == null ? "" : " " + order) + (limit == null ? "" : " " + where == null ? "WHERE " + limit : limit); else sql = sql + (where == null ? "" : " " + where) + (order == null ? "" : " " + order) + (limit == null ? "" : " " + limit); return sql; } private <T> Cursor<T> openCursor(final Transaction txn, final Cache cache, final Class<T> type, final String sql) throws OperationTimeoutException, DataProviderException { return openCursor(txn, cache, type, sql, Collections.emptyList()); } private <T> Cursor<T> openCursor(final Transaction txn, final Cache cache, final Class<T> type, final String sql, List<Object> values) throws OperationTimeoutException, DataProviderException { Cursor<T> cursor = null; final Connection conn = getConnection(txn); try { final List<T> lrs = new ArrayList<T>(); final PreparedStatement pst = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); pst.setFetchSize(fetchSize.intValue()); setQueryTimeout(pst); if (!values.isEmpty()) { int parameterIndex = 1; for (final Object value : values) { if (value instanceof TimeUnit) { final String unit = EntityUtils.parseTimeUnit((TimeUnit) value); pst.setObject(parameterIndex++, unit); } else if (value instanceof Enum<?>) { pst.setObject(parameterIndex++, value.toString()); } else { pst.setObject(parameterIndex++, value); } } } final ResultSet rs = pst.executeQuery(); while (rs.next()) { final T bean = makeEntity(type, rs); // Instantiate and populate a new bean cacheIt(txn, cache, bean); // Caches the new bean lrs.add(bean); // Adds to the cursor collection } rs.close(); T[] resultSet = (T[]) Array.newInstance(type, lrs.size()); System.arraycopy(lrs.toArray(), 0, resultSet, 0, lrs.size()); lrs.clear(); cursor = new SimpleCursor<T>(resultSet); } catch (final SQLTimeoutException e) { throw new OperationTimeoutException("The currently executing 'cursor*' operation is timed out", e); } catch (final SQLException sqle) { throw new DataProviderException("Could not execute the database statement", sqle); } finally { close(txn, conn); } return cursor; } /** * Assembles a new entity object based on the content of the current result set position. * * @param type * @param rs * * @return * * @throws IllegalArgumentException * @throws SQLException */ @SuppressWarnings("rawtypes") private <T> T makeEntity(final Class<T> type, final ResultSet rs) throws IllegalArgumentException, SQLException { T bean = null; final ResultSetMetaData meta = rs.getMetaData(); try { bean = type.newInstance(); } catch (final InstantiationException e) { return null; } catch (final IllegalAccessException e) { return null; } // FIXME support for all SQL/Java types for (int i = 1; i <= meta.getColumnCount(); i++) { final Object value = rs.getObject(i); if (rs.wasNull()) continue; final String colName = meta.getColumnName(i); final ElementInfo einfo = EntityUtils.info(bean.getClass(), colName); if (einfo == null) continue; final Class<?> beanFieldType = einfo.type(); if (beanFieldType.equals(TimeUnit.class)) { EntityUtils.value(bean, colName, EntityUtils.parseTimeUnit((String) value)); } else if (beanFieldType.isEnum()) { EntityUtils.value(bean, colName, Enum.valueOf((Class<Enum>) beanFieldType, (String) value)); } // else if (value instanceof Date) // { // BeanUtils.value(bean, colName, ((Date) value).getTime()); // } // else if (value instanceof Timestamp) // { // BeanUtils.value(bean, colName, ((Timestamp) value).getTime()); // } else if (value instanceof Integer) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, value); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, new Long(((Integer) value))); else if (beanFieldType.equals(Boolean.class)) EntityUtils.value(bean, colName, ((Integer) value) == 1 ? true : false); else EntityUtils.value(bean, colName, value); } else if (value instanceof Long) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, ((Long) value).intValue()); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, value); else EntityUtils.value(bean, colName, value); } else if (value instanceof BigDecimal) { if (beanFieldType.equals(Integer.class)) EntityUtils.value(bean, colName, ((BigDecimal) value).intValue()); else if (beanFieldType.equals(Long.class)) EntityUtils.value(bean, colName, ((BigDecimal) value).longValue()); else EntityUtils.value(bean, colName, value); } else { EntityUtils.value(bean, colName, value); } } return bean; } /** * Caches the given bean into the given cache only if there is no current transaction in * progress. * * @param cache * the cache instance * @param eban * the bean to be cached */ private void cacheIt(final Transaction txn, final Cache cache, final Object bean) { if (!transactionInProgress(txn)) cache.add(bean); // Save to cache it } /** * Retrieves the connection from the current transaction. If there is no transaction, try to * acquire a transaction from the providers pool. * * @param txn * the current transaction object; can be {@code null} with there is no transaction * * @return the connection * * @throws NotEnoughResourceException * if a database access error occurs */ private Connection getConnection(final Transaction txn) throws NotEnoughResourceException { return txn == null ? provider.getConnection() : ((JdbcTransactionImpl) txn).getConnection(); } /** * Sets the query timeout to the given Statement object. * * @param st * the Statement object to set * * @throws SQLException * if a database access error occurs * @throws SQLException * if this method is called on a closed Statement * @throws SQLException * if the condition seconds >= 0 is not satisfied */ private void setQueryTimeout(final Statement st) throws SQLException { if (queryTimeout > 0L) { st.setQueryTimeout(queryTimeout.intValue()); } } /** * Commits the given connection. If the connection is participating in a transaction this call * has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to commit * * @throws SQLException * if a database access error occurs */ private void commit(final Transaction txn, final Connection conn) throws SQLException { if (txn == null) { conn.commit(); } } /** * Roll backs the given connection. If the connection is participating in a transaction this * call has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to roll back * * @throws SQLException * if a database access error occurs */ private void rollback(final Transaction txn, final Connection conn) throws SQLException { if (txn == null) { conn.rollback(); } } /** * Closes the given connection. If the connection is participating in a transaction this call * has no effect. * * @param txn * the current transaction or {@code null} when there is no active transaction * @param conn * the {@link Connection} to close * * @throws DataProviderException * if a database access error occurs */ private void close(final Transaction txn, final Connection conn) throws DataProviderException { if (txn == null) { try { conn.close(); } catch (final SQLException e) { throw new DataProviderException("Could not close the database connection", e); } } } }
Fix offset/limit statement for MySQL
udao-provider-jdbc/src/main/java/io/perbone/udao/provider/jdbc/JdbcDataSourceImpl.java
Fix offset/limit statement for MySQL
<ide><path>dao-provider-jdbc/src/main/java/io/perbone/udao/provider/jdbc/JdbcDataSourceImpl.java <ide> query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset() - 1) : 0L); <ide> break; <ide> case MYSQL: <del> limit = String.format(" LIMIT %d,%d", query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset()) : 0L, <del> query.limit()); <add> limit = String.format(" LIMIT %d,%d", <add> query.hasOffset() ? (query.offset() == 1 ? 0L : query.offset() - 1) : 0L, query.limit()); <ide> break; <ide> case DERBY: <ide> limit = String.format(" OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", query.hasOffset() ? query.offset() : 0L,
Java
lgpl-2.1
8c570650bb5738572fe3a0903e503abb4ea5b6d2
0
anddann/soot,xph906/SootNew,plast-lab/soot,xph906/SootNew,xph906/SootNew,cfallin/soot,anddann/soot,plast-lab/soot,cfallin/soot,cfallin/soot,mbenz89/soot,mbenz89/soot,mbenz89/soot,xph906/SootNew,mbenz89/soot,anddann/soot,anddann/soot,cfallin/soot,plast-lab/soot
/* Soot - a J*va Optimization Framework * Copyright (C) 2007 Manu Sridharan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.spark.ondemand; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.AnySubType; import soot.ArrayType; import soot.Context; import soot.G; import soot.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.RefType; import soot.Scene; import soot.SootField; import soot.SootMethod; import soot.Type; import soot.jimple.spark.ondemand.genericutil.ArraySet; import soot.jimple.spark.ondemand.genericutil.HashSetMultiMap; import soot.jimple.spark.ondemand.genericutil.ImmutableStack; import soot.jimple.spark.ondemand.genericutil.Predicate; import soot.jimple.spark.ondemand.genericutil.Propagator; import soot.jimple.spark.ondemand.genericutil.Stack; import soot.jimple.spark.ondemand.pautil.AssignEdge; import soot.jimple.spark.ondemand.pautil.ContextSensitiveInfo; import soot.jimple.spark.ondemand.pautil.OTFMethodSCCManager; import soot.jimple.spark.ondemand.pautil.SootUtil; import soot.jimple.spark.ondemand.pautil.ValidMatches; import soot.jimple.spark.ondemand.pautil.SootUtil.FieldToEdgesMap; import soot.jimple.spark.pag.AllocNode; import soot.jimple.spark.pag.FieldRefNode; import soot.jimple.spark.pag.GlobalVarNode; import soot.jimple.spark.pag.LocalVarNode; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import soot.jimple.spark.pag.SparkField; import soot.jimple.spark.pag.VarNode; import soot.jimple.spark.sets.EmptyPointsToSet; import soot.jimple.spark.sets.HybridPointsToSet; import soot.jimple.spark.sets.P2SetVisitor; import soot.jimple.spark.sets.PointsToSetInternal; import soot.jimple.toolkits.callgraph.VirtualCalls; import soot.toolkits.scalar.Pair; import soot.util.NumberedString; /** * Tries to find imprecision in points-to sets from a previously run analysis. * Requires that all sub-results of previous analysis were cached. * * @author Manu Sridharan * */ public final class DemandCSPointsTo implements PointsToAnalysis { @SuppressWarnings("serial") protected static final class AllocAndContextCache extends HashMap<AllocAndContext, Map<VarNode, CallingContextSet>> { } protected static final class CallingContextSet extends ArraySet<ImmutableStack<Integer>> { } protected final static class CallSiteAndContext extends Pair<Integer, ImmutableStack<Integer>> { public CallSiteAndContext(Integer callSite, ImmutableStack<Integer> callingContext) { super(callSite, callingContext); } } protected static final class CallSiteToTargetsMap extends HashSetMultiMap<CallSiteAndContext, SootMethod> { } protected static abstract class IncomingEdgeHandler { public abstract void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext); public abstract void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine); abstract Object getResult(); abstract void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge); abstract boolean shouldHandleSrc(VarNode src); boolean terminate() { return false; } } protected static class VarAndContext { final ImmutableStack<Integer> context; final VarNode var; public VarAndContext(VarNode var, ImmutableStack<Integer> context) { assert var != null; assert context != null; this.var = var; this.context = context; } public boolean equals(Object o) { if (o != null && o.getClass() == VarAndContext.class) { VarAndContext other = (VarAndContext) o; return var.equals(other.var) && context.equals(other.context); } return false; } public int hashCode() { return var.hashCode() + context.hashCode(); } public String toString() { return var + " " + context; } } protected final static class VarContextAndUp extends VarAndContext { final ImmutableStack<Integer> upContext; public VarContextAndUp(VarNode var, ImmutableStack<Integer> context, ImmutableStack<Integer> upContext) { super(var, context); this.upContext = upContext; } public boolean equals(Object o) { if (o != null && o.getClass() == VarContextAndUp.class) { VarContextAndUp other = (VarContextAndUp) o; return var.equals(other.var) && context.equals(other.context) && upContext.equals(other.upContext); } return false; } public int hashCode() { return var.hashCode() + context.hashCode() + upContext.hashCode(); } public String toString() { return var + " " + context + " up " + upContext; } } protected static final boolean DEBUG = false; protected static final int DEBUG_NESTING = 15; protected static final int DEBUG_PASS = -1; protected static final boolean DEBUG_VIRT = DEBUG && true; protected static final int DEFAULT_MAX_PASSES = 10; protected static final int DEFAULT_MAX_TRAVERSAL = 75000; /** * if <code>true</code>, refine the pre-computed call graph */ private boolean refineCallGraph = true; protected static final ImmutableStack<Integer> EMPTY_CALLSTACK = ImmutableStack.<Integer> emptyStack(); /** * Make a default analysis. Assumes Spark has already run. * * @return */ public static DemandCSPointsTo makeDefault() { return makeWithBudget(DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES); } public static DemandCSPointsTo makeWithBudget(int maxTraversal, int maxPasses) { PAG pag = (PAG) Scene.v().getPointsToAnalysis(); ContextSensitiveInfo csInfo = new ContextSensitiveInfo(pag); return new DemandCSPointsTo(csInfo, pag, maxTraversal, maxPasses); } protected final AllocAndContextCache allocAndContextCache = new AllocAndContextCache(); protected Stack<Pair<Integer, ImmutableStack<Integer>>> callGraphStack = new Stack<Pair<Integer, ImmutableStack<Integer>>>(); protected final CallSiteToTargetsMap callSiteToResolvedTargets = new CallSiteToTargetsMap(); protected HashMap<List<Object>, Set<SootMethod>> callTargetsArgCache = new HashMap<List<Object>, Set<SootMethod>>(); protected final Stack<VarAndContext> contextForAllocsStack = new Stack<VarAndContext>(); protected Map<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>> contextsForAllocsCache = new HashMap<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>>(); protected final ContextSensitiveInfo csInfo; protected boolean doPointsTo; protected FieldCheckHeuristic fieldCheckHeuristic; protected final FieldToEdgesMap fieldToLoads; protected final FieldToEdgesMap fieldToStores; protected final int maxNodesPerPass; protected final int maxPasses; protected int nesting = 0; protected int numNodesTraversed; protected int numPasses = 0; protected final PAG pag; protected AllocAndContextSet pointsTo = null; protected final Set<CallSiteAndContext> queriedCallSites = new HashSet<CallSiteAndContext>(); protected int recursionDepth = -1; protected boolean refiningCallSite = false; protected OTFMethodSCCManager sccManager; protected Map<VarContextAndUp, Map<AllocAndContext, CallingContextSet>> upContextCache = new HashMap<VarContextAndUp, Map<AllocAndContext, CallingContextSet>>(); protected final ValidMatches vMatches; protected Map<Local,PointsToSet> reachingObjectsCache; protected boolean useCache; public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag) { this(csInfo, pag, DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES); } public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag, int maxTraversal, int maxPasses) { this.csInfo = csInfo; this.pag = pag; this.fieldToStores = SootUtil.storesOnField(pag); this.fieldToLoads = SootUtil.loadsOnField(pag); this.vMatches = new ValidMatches(pag, fieldToStores); this.maxPasses = maxPasses; this.maxNodesPerPass = maxTraversal / maxPasses; this.fieldCheckHeuristic = HeuristicType.getHeuristic( HeuristicType.INCR, pag.getTypeManager(), getMaxPasses()); this.reachingObjectsCache = new HashMap<Local, PointsToSet>(); this.useCache = true; } /** * {@inheritDoc} */ public PointsToSet reachingObjects(Local l) { PointsToSet result = reachingObjectsCache.get(l); if(result==null) { result = computeReachingObjects(l); if(useCache) { reachingObjectsCache.put(l, result); } } return result; } /** * Computes the possibly refined set of reaching objects for l. */ protected PointsToSet computeReachingObjects(Local l) { VarNode v = pag.findLocalVarNode(l); if (v == null) { //no reaching objects return EmptyPointsToSet.v(); } PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v); if(contextSensitiveResult == null ) { //had to abort; return Spark's points-to set in a wrapper return new WrappedPointsToSet(v.getP2Set()); } else { return contextSensitiveResult; } } /** * Computes the refined set of reaching objects for l. * Returns <code>null</code> if refinement failed. */ protected PointsToSet computeRefinedReachingObjects(VarNode v) { // must reset the refinement heuristic for each query this.fieldCheckHeuristic = HeuristicType.getHeuristic( HeuristicType.INCR, pag.getTypeManager(), getMaxPasses()); doPointsTo = true; numPasses = 0; PointsToSet contextSensitiveResult = null; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { break; } if (numPasses > maxPasses) { break; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); pointsTo = new AllocAndContextSet(); try { refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null); contextSensitiveResult = pointsTo; } catch (TerminateEarlyException e) { } if (!fieldCheckHeuristic.runNewPass()) { break; } } return contextSensitiveResult; } protected boolean callEdgeInSCC(AssignEdge assignEdge) { boolean sameSCCAlready = false; assert assignEdge.isCallEdge(); // assert assignEdge.getSrc() instanceof LocalVarNode : // assignEdge.getSrc() + " not LocalVarNode"; if (!(assignEdge.getSrc() instanceof LocalVarNode) || !(assignEdge.getDst() instanceof LocalVarNode)) { return false; } LocalVarNode src = (LocalVarNode) assignEdge.getSrc(); LocalVarNode dst = (LocalVarNode) assignEdge.getDst(); if (sccManager.inSameSCC(src.getMethod(), dst.getMethod())) { sameSCCAlready = true; } return sameSCCAlready; } protected CallingContextSet checkAllocAndContextCache( AllocAndContext allocAndContext, VarNode targetVar) { if (allocAndContextCache.containsKey(allocAndContext)) { Map<VarNode, CallingContextSet> m = allocAndContextCache .get(allocAndContext); if (m.containsKey(targetVar)) { return m.get(targetVar); } } else { allocAndContextCache.put(allocAndContext, new HashMap<VarNode, CallingContextSet>()); } return null; } protected PointsToSetInternal checkContextsForAllocsCache( VarAndContext varAndContext, AllocAndContextSet ret, PointsToSetInternal locs) { PointsToSetInternal retSet = null; if (contextsForAllocsCache.containsKey(varAndContext)) { for (AllocAndContext allocAndContext : contextsForAllocsCache.get( varAndContext).getO2()) { if (locs.contains(allocAndContext.alloc)) { ret.add(allocAndContext); } } final PointsToSetInternal oldLocs = contextsForAllocsCache.get( varAndContext).getO1(); final PointsToSetInternal tmpSet = new HybridPointsToSet(locs .getType(), pag); locs.forall(new P2SetVisitor() { @Override public void visit(Node n) { if (!oldLocs.contains(n)) { tmpSet.add(n); } } }); retSet = tmpSet; oldLocs.addAll(tmpSet, null); } else { PointsToSetInternal storedSet = new HybridPointsToSet(locs .getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache.put(varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, new AllocAndContextSet())); retSet = locs; } return retSet; } /** * check the computed points-to set of a variable against some predicate * * @param v * the variable * @param heuristic * how to refine match edges * @param p2setPred * the predicate on the points-to set * @return true if the p2setPred holds for the computed points-to set, or if * a points-to set cannot be computed in the budget; false otherwise */ protected boolean checkP2Set(VarNode v, HeuristicType heuristic, Predicate<Set<AllocAndContext>> p2setPred) { doPointsTo = true; // DEBUG = v.getNumber() == 150; this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return true; } if (numPasses > maxPasses) { return true; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); pointsTo = new AllocAndContextSet(); boolean success = false; try { success = refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null); } catch (TerminateEarlyException e) { success = false; } if (success) { if (p2setPred.test(pointsTo)) { return false; } } else { if (!fieldCheckHeuristic.runNewPass()) { return true; } } } } // protected boolean upContextsSane(CallingContextSet ret, AllocAndContext // allocAndContext, VarContextAndUp varContextAndUp) { // for (ImmutableStack<Integer> context : ret) { // ImmutableStack<Integer> fixedContext = fixUpContext(context, // allocAndContext, varContextAndUp); // if (!context.equals(fixedContext)) { // return false; // } // } // return true; // } // // protected CallingContextSet fixAllUpContexts(CallingContextSet contexts, // AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) { // if (DEBUG) { // debugPrint("fixing up contexts"); // } // CallingContextSet ret = new CallingContextSet(); // for (ImmutableStack<Integer> context : contexts) { // ret.add(fixUpContext(context, allocAndContext, varContextAndUp)); // } // return ret; // } // // protected ImmutableStack<Integer> fixUpContext(ImmutableStack<Integer> // context, AllocAndContext allocAndContext, VarContextAndUp // varContextAndUp) { // // return null; // } protected CallingContextSet checkUpContextCache( VarContextAndUp varContextAndUp, AllocAndContext allocAndContext) { if (upContextCache.containsKey(varContextAndUp)) { Map<AllocAndContext, CallingContextSet> allocAndContextMap = upContextCache .get(varContextAndUp); if (allocAndContextMap.containsKey(allocAndContext)) { return allocAndContextMap.get(allocAndContext); } } else { upContextCache.put(varContextAndUp, new HashMap<AllocAndContext, CallingContextSet>()); } return null; } protected void clearState() { allocAndContextCache.clear(); callGraphStack.clear(); callSiteToResolvedTargets.clear(); queriedCallSites.clear(); contextsForAllocsCache.clear(); contextForAllocsStack.clear(); upContextCache.clear(); callTargetsArgCache.clear(); sccManager = new OTFMethodSCCManager(); numNodesTraversed = 0; nesting = 0; recursionDepth = -1; } /** * compute a flows-to set for an allocation site. for now, we use a simple * refinement strategy; just refine as much as possible, maintaining the * smallest set of flows-to vars * * @param alloc * @param heuristic * @return */ protected Set<VarNode> computeFlowsTo(AllocNode alloc, HeuristicType heuristic) { this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; Set<VarNode> smallest = null; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return smallest; } if (numPasses > maxPasses) { return smallest; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); Set<VarNode> result = null; try { result = getFlowsToHelper(new AllocAndContext(alloc, EMPTY_CALLSTACK)); } catch (TerminateEarlyException e) { } if (result != null) { if (smallest == null || result.size() < smallest.size()) { smallest = result; } } if (!fieldCheckHeuristic.runNewPass()) { return smallest; } } } protected void debugPrint(String str) { if (nesting <= DEBUG_NESTING) { if (DEBUG_PASS == -1 || DEBUG_PASS == numPasses) { G.v().out.println(":" + nesting + " " + str); } } } /* * (non-Javadoc) * * @see AAA.summary.Refiner#dumpPathForBadLoc(soot.jimple.spark.pag.VarNode, * soot.jimple.spark.pag.AllocNode) */ protected void dumpPathForLoc(VarNode v, final AllocNode badLoc, String filePrefix) { final HashSet<VarNode> visited = new HashSet<VarNode>(); final DotPointerGraph dotGraph = new DotPointerGraph(); final class Helper { boolean handle(VarNode curNode) { assert curNode.getP2Set().contains(badLoc); visited.add(curNode); Node[] newEdges = pag.allocInvLookup(curNode); for (int i = 0; i < newEdges.length; i++) { AllocNode alloc = (AllocNode) newEdges[i]; if (alloc.equals(badLoc)) { dotGraph.addNew(alloc, curNode); return true; } } for (AssignEdge assignEdge : csInfo.getAssignEdges(curNode)) { VarNode other = assignEdge.getSrc(); if (other.getP2Set().contains(badLoc) && !visited.contains(other) && handle(other)) { if (assignEdge.isCallEdge()) { dotGraph.addCall(other, curNode, assignEdge .getCallSite()); } else { dotGraph.addAssign(other, curNode); } return true; } } Node[] loadEdges = pag.loadInvLookup(curNode); for (int i = 0; i < loadEdges.length; i++) { FieldRefNode frNode = (FieldRefNode) loadEdges[i]; SparkField field = frNode.getField(); VarNode base = frNode.getBase(); PointsToSetInternal baseP2Set = base.getP2Set(); for (Pair<VarNode, VarNode> store : fieldToStores .get(field)) { if (store.getO2().getP2Set().hasNonEmptyIntersection( baseP2Set)) { VarNode matchSrc = store.getO1(); if (matchSrc.getP2Set().contains(badLoc) && !visited.contains(matchSrc) && handle(matchSrc)) { dotGraph.addMatch(matchSrc, curNode); return true; } } } } return false; } } Helper h = new Helper(); h.handle(v); // G.v().out.println(dotGraph.numEdges() + " edges on path"); dotGraph.dump("tmp/" + filePrefix + v.getNumber() + "_" + badLoc.getNumber() + ".dot"); } protected Collection<AssignEdge> filterAssigns(final VarNode v, final ImmutableStack<Integer> callingContext, boolean forward, boolean refineVirtCalls) { Set<AssignEdge> assigns = forward ? csInfo.getAssignEdges(v) : csInfo .getAssignBarEdges(v); Collection<AssignEdge> realAssigns; boolean exitNode = forward ? SootUtil.isParamNode(v) : SootUtil .isRetNode(v); final boolean backward = !forward; if (exitNode && !callingContext.isEmpty()) { Integer topCallSite = callingContext.peek(); realAssigns = new ArrayList<AssignEdge>(); for (AssignEdge assignEdge : assigns) { assert (forward && assignEdge.isParamEdge()) || (backward && assignEdge.isReturnEdge()) : assignEdge; Integer assignEdgeCallSite = assignEdge.getCallSite(); assert csInfo.getCallSiteTargets(assignEdgeCallSite).contains( ((LocalVarNode) v).getMethod()) : assignEdge; if (topCallSite.equals(assignEdgeCallSite) || callEdgeInSCC(assignEdge)) { realAssigns.add(assignEdge); } } // assert realAssigns.size() == 1; } else { if (assigns.size() > 1) { realAssigns = new ArrayList<AssignEdge>(); for (AssignEdge assignEdge : assigns) { boolean enteringCall = forward ? assignEdge.isReturnEdge() : assignEdge.isParamEdge(); if (enteringCall) { Integer callSite = assignEdge.getCallSite(); if (csInfo.isVirtCall(callSite) && refineVirtCalls) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), callingContext); LocalVarNode nodeInTargetMethod = forward ? (LocalVarNode) assignEdge .getSrc() : (LocalVarNode) assignEdge.getDst(); if (targets .contains(nodeInTargetMethod.getMethod())) { realAssigns.add(assignEdge); } } else { realAssigns.add(assignEdge); } } else { realAssigns.add(assignEdge); } } } else { realAssigns = assigns; } } return realAssigns; } protected AllocAndContextSet findContextsForAllocs( final VarAndContext varAndContext, PointsToSetInternal locs) { if (contextForAllocsStack.contains(varAndContext)) { // recursion; check depth // we're fine for x = x.next int oldIndex = contextForAllocsStack.indexOf(varAndContext); if (oldIndex != contextForAllocsStack.size() - 1) { if (recursionDepth == -1) { recursionDepth = oldIndex + 1; if (DEBUG) { debugPrint("RECURSION depth = " + recursionDepth); } } else if (contextForAllocsStack.size() - oldIndex > 5) { // just give up throw new TerminateEarlyException(); } } } contextForAllocsStack.push(varAndContext); final AllocAndContextSet ret = new AllocAndContextSet(); final PointsToSetInternal realLocs = checkContextsForAllocsCache( varAndContext, ret, locs); if (realLocs.isEmpty()) { if (DEBUG) { debugPrint("cached result " + ret); } contextForAllocsStack.pop(); return ret; } nesting++; if (DEBUG) { debugPrint("finding alloc contexts for " + varAndContext); } try { final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varAndContext); IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() { @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { if (realLocs.contains(allocNode)) { if (DEBUG) { debugPrint("found alloc " + allocNode); } ret.add(new AllocAndContext(allocNode, origVarAndContext.context)); } } @Override public void handleMatchSrc(final VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { if (DEBUG) { debugPrint("handling src " + matchSrc); debugPrint("intersection " + intersection); } if (!refine) { p.prop(new VarAndContext(matchSrc, EMPTY_CALLSTACK)); return; } AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(loadBase, origVarAndContext.context), intersection); if (DEBUG) { debugPrint("alloc contexts " + allocContexts); } for (AllocAndContext allocAndContext : allocContexts) { if (DEBUG) { debugPrint("alloc and context " + allocAndContext); } CallingContextSet matchSrcContexts; if (fieldCheckHeuristic.validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp( storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { // ret // .add(new Pair<AllocNode, // ImmutableStack<Integer>>( // (AllocNode) n, // matchSrcContext)); // ret.addAll(findContextsForAllocs(matchSrc, // matchSrcContext, locs)); p .prop(new VarAndContext(matchSrc, matchSrcContext)); } } } @Override Object getResult() { return ret; } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { p.prop(newVarAndContext); } @Override boolean shouldHandleSrc(VarNode src) { return realLocs.hasNonEmptyIntersection(src.getP2Set()); } }; processIncomingEdges(edgeHandler, worklist); // update the cache if (recursionDepth != -1) { // if we're beyond recursion, don't cache anything if (contextForAllocsStack.size() > recursionDepth) { if (DEBUG) { debugPrint("REMOVING " + varAndContext); debugPrint(contextForAllocsStack.toString()); } contextsForAllocsCache.remove(varAndContext); } else { assert contextForAllocsStack.size() == recursionDepth : recursionDepth + " " + contextForAllocsStack; recursionDepth = -1; if (contextsForAllocsCache.containsKey(varAndContext)) { contextsForAllocsCache.get(varAndContext).getO2() .addAll(ret); } else { PointsToSetInternal storedSet = new HybridPointsToSet( locs.getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache .put( varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, ret)); } } } else { if (contextsForAllocsCache.containsKey(varAndContext)) { contextsForAllocsCache.get(varAndContext).getO2().addAll( ret); } else { PointsToSetInternal storedSet = new HybridPointsToSet(locs .getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache.put(varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, ret)); } } nesting--; return ret; } catch (CallSiteException e) { contextsForAllocsCache.remove(varAndContext); throw e; } finally { contextForAllocsStack.pop(); } } protected CallingContextSet findUpContextsForVar( AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) { final AllocNode alloc = allocAndContext.alloc; final ImmutableStack<Integer> allocContext = allocAndContext.context; CallingContextSet tmpSet = checkUpContextCache(varContextAndUp, allocAndContext); if (tmpSet != null) { return tmpSet; } final CallingContextSet ret = new CallingContextSet(); upContextCache.get(varContextAndUp).put(allocAndContext, ret); nesting++; if (DEBUG) { debugPrint("finding up context for " + varContextAndUp + " to " + alloc + " " + allocContext); } try { final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varContextAndUp); class UpContextEdgeHandler extends IncomingEdgeHandler { @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; if (allocNode == alloc) { if (allocContext.topMatches(contextAndUp.context)) { ImmutableStack<Integer> reverse = contextAndUp.upContext .reverse(); ImmutableStack<Integer> toAdd = allocContext .popAll(contextAndUp.context).pushAll( reverse); if (DEBUG) { debugPrint("found up context " + toAdd); } ret.add(toAdd); } else if (contextAndUp.context .topMatches(allocContext)) { ImmutableStack<Integer> toAdd = contextAndUp.upContext .reverse(); if (DEBUG) { debugPrint("found up context " + toAdd); } ret.add(toAdd); } } } @Override public void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; if (DEBUG) { debugPrint("CHECKING " + alloc); } PointsToSetInternal tmp = new HybridPointsToSet(alloc .getType(), pag); tmp.add(alloc); AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(matchSrc, EMPTY_CALLSTACK), tmp); // Set allocContexts = Collections.singleton(new Object()); if (!refine) { if (!allocContexts.isEmpty()) { ret.add(contextAndUp.upContext.reverse()); } } else { if (!allocContexts.isEmpty()) { for (AllocAndContext t : allocContexts) { ImmutableStack<Integer> discoveredAllocContext = t.context; if (!allocContext .topMatches(discoveredAllocContext)) { continue; } ImmutableStack<Integer> trueAllocContext = allocContext .popAll(discoveredAllocContext); AllocAndContextSet allocAndContexts = findContextsForAllocs( new VarAndContext(storeBase, trueAllocContext), intersection); for (AllocAndContext allocAndContext : allocAndContexts) { // if (DEBUG) // G.v().out.println("alloc context " // + newAllocContext); // CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { ret .addAll(findUpContextsForVar( allocAndContext, new VarContextAndUp( loadBase, contextAndUp.context, contextAndUp.upContext))); } else { CallingContextSet tmpContexts = findVarContextsFromAlloc( allocAndContext, loadBase); // upContexts = new CallingContextSet(); for (ImmutableStack<Integer> tmpContext : tmpContexts) { if (tmpContext .topMatches(contextAndUp.context)) { ImmutableStack<Integer> reverse = contextAndUp.upContext .reverse(); ImmutableStack<Integer> toAdd = tmpContext .popAll( contextAndUp.context) .pushAll(reverse); ret.add(toAdd); } } } } } } } } @Override Object getResult() { return ret; } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; ImmutableStack<Integer> upContext = contextAndUp.upContext; ImmutableStack<Integer> newUpContext = upContext; if (assignEdge.isParamEdge() && contextAndUp.context.isEmpty()) { if (upContext.size() < ImmutableStack.getMaxSize()) { newUpContext = pushWithRecursionCheck(upContext, assignEdge); } ; } p.prop(new VarContextAndUp(newVarAndContext.var, newVarAndContext.context, newUpContext)); } @Override boolean shouldHandleSrc(VarNode src) { if (src instanceof GlobalVarNode) { // TODO properly handle case of global here; rare // but possible // reachedGlobal = true; // // for now, just give up throw new TerminateEarlyException(); } return src.getP2Set().contains(alloc); } } ; UpContextEdgeHandler edgeHandler = new UpContextEdgeHandler(); processIncomingEdges(edgeHandler, worklist); nesting--; // if (edgeHandler.reachedGlobal) { // return fixAllUpContexts(ret, allocAndContext, varContextAndUp); // } else { // assert upContextsSane(ret, allocAndContext, varContextAndUp); // return ret; // } return ret; } catch (CallSiteException e) { upContextCache.remove(varContextAndUp); throw e; } } protected CallingContextSet findVarContextsFromAlloc( AllocAndContext allocAndContext, VarNode targetVar) { CallingContextSet tmpSet = checkAllocAndContextCache(allocAndContext, targetVar); if (tmpSet != null) { return tmpSet; } CallingContextSet ret = new CallingContextSet(); allocAndContextCache.get(allocAndContext).put(targetVar, ret); try { HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); Stack<VarAndContext> worklist = new Stack<VarAndContext>(); Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked, worklist); AllocNode alloc = allocAndContext.alloc; ImmutableStack<Integer> allocContext = allocAndContext.context; Node[] newBarNodes = pag.allocLookup(alloc); for (int i = 0; i < newBarNodes.length; i++) { VarNode v = (VarNode) newBarNodes[i]; p.prop(new VarAndContext(v, allocContext)); } while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; if (curVar == targetVar) { ret.add(curContext); } // assign Collection<AssignEdge> assignEdges = filterAssigns(curVar, curContext, false, true); for (AssignEdge assignEdge : assignEdges) { VarNode dst = assignEdge.getDst(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isReturnEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()) : assignEdge + " " + curContext; newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } } else if (assignEdge.isParamEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } if (assignEdge.isReturnEdge() && curContext.isEmpty() && csInfo.isVirtCall(assignEdge.getCallSite())) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), newContext); if (!targets.contains(((LocalVarNode) assignEdge .getDst()).getMethod())) { continue; } } if (dst instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } p.prop(new VarAndContext(dst, newContext)); } // putfield_bars Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar); Node[] pfTargets = pag.storeLookup(curVar); for (int i = 0; i < pfTargets.length; i++) { FieldRefNode frNode = (FieldRefNode) pfTargets[i]; final VarNode storeBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode, // FieldRefNode>(curVar, frNode); for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) { final VarNode loadBase = load.getO2(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final VarNode matchTgt = load.getO1(); if (matchTargets.contains(matchTgt)) { if (DEBUG) { debugPrint("match source " + matchTgt); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkField = fieldCheckHeuristic .validateMatchesForField(field); if (checkField) { AllocAndContextSet sharedAllocContexts = findContextsForAllocs( new VarAndContext(storeBase, curContext), intersection); for (AllocAndContext curAllocAndContext : sharedAllocContexts) { CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { upContexts = findUpContextsForVar( curAllocAndContext, new VarContextAndUp(loadBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { upContexts = findVarContextsFromAlloc( curAllocAndContext, loadBase); } for (ImmutableStack<Integer> upContext : upContexts) { p.prop(new VarAndContext(matchTgt, upContext)); } } } else { p.prop(new VarAndContext(matchTgt, EMPTY_CALLSTACK)); } // h.handleMatchSrc(matchSrc, intersection, // storeBase, // loadBase, varAndContext, checkGetfield); // if (h.terminate()) // return; } } } } return ret; } catch (CallSiteException e) { allocAndContextCache.remove(allocAndContext); throw e; } } @SuppressWarnings("unchecked") protected Set<SootMethod> getCallTargets(PointsToSetInternal p2Set, NumberedString methodStr, Type receiverType, Set<SootMethod> possibleTargets) { List<Object> args = Arrays.asList(p2Set, methodStr, receiverType, possibleTargets); if (callTargetsArgCache.containsKey(args)) { return callTargetsArgCache.get(args); } Set<Type> types = p2Set.possibleTypes(); Set<SootMethod> ret = new HashSet<SootMethod>(); for (Type type : types) { ret.addAll(getCallTargetsForType(type, methodStr, receiverType, possibleTargets)); } callTargetsArgCache.put(args, ret); return ret; } protected Set<SootMethod> getCallTargetsForType(Type type, NumberedString methodStr, Type receiverType, Set<SootMethod> possibleTargets) { if (!pag.getTypeManager().castNeverFails(type, receiverType)) return Collections.<SootMethod> emptySet(); if (type instanceof AnySubType) { AnySubType any = (AnySubType) type; RefType refType = any.getBase(); if (pag.getTypeManager().getFastHierarchy().canStoreType( receiverType, refType) || pag.getTypeManager().getFastHierarchy().canStoreType( refType, receiverType)) { return possibleTargets; } else { return Collections.<SootMethod> emptySet(); } } if (type instanceof ArrayType) { // we'll invoke the java.lang.Object method in this // case // Assert.chk(varNodeType.toString().equals("java.lang.Object")); type = Scene.v().getSootClass("java.lang.Object").getType(); } RefType refType = (RefType) type; SootMethod targetMethod = null; targetMethod = VirtualCalls.v().resolveNonSpecial(refType, methodStr); return Collections.<SootMethod> singleton(targetMethod); } protected Set<VarNode> getFlowsToHelper(AllocAndContext allocAndContext) { Set<VarNode> ret = new ArraySet<VarNode>(); try { HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); Stack<VarAndContext> worklist = new Stack<VarAndContext>(); Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked, worklist); AllocNode alloc = allocAndContext.alloc; ImmutableStack<Integer> allocContext = allocAndContext.context; Node[] newBarNodes = pag.allocLookup(alloc); for (int i = 0; i < newBarNodes.length; i++) { VarNode v = (VarNode) newBarNodes[i]; ret.add(v); p.prop(new VarAndContext(v, allocContext)); } while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; ret.add(curVar); // assign Collection<AssignEdge> assignEdges = filterAssigns(curVar, curContext, false, true); for (AssignEdge assignEdge : assignEdges) { VarNode dst = assignEdge.getDst(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isReturnEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()) : assignEdge + " " + curContext; newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } } else if (assignEdge.isParamEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } if (assignEdge.isReturnEdge() && curContext.isEmpty() && csInfo.isVirtCall(assignEdge.getCallSite())) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), newContext); if (!targets.contains(((LocalVarNode) assignEdge .getDst()).getMethod())) { continue; } } if (dst instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } p.prop(new VarAndContext(dst, newContext)); } // putfield_bars Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar); Node[] pfTargets = pag.storeLookup(curVar); for (int i = 0; i < pfTargets.length; i++) { FieldRefNode frNode = (FieldRefNode) pfTargets[i]; final VarNode storeBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode, // FieldRefNode>(curVar, frNode); for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) { final VarNode loadBase = load.getO2(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final VarNode matchTgt = load.getO1(); if (matchTargets.contains(matchTgt)) { if (DEBUG) { debugPrint("match source " + matchTgt); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkField = fieldCheckHeuristic .validateMatchesForField(field); if (checkField) { AllocAndContextSet sharedAllocContexts = findContextsForAllocs( new VarAndContext(storeBase, curContext), intersection); for (AllocAndContext curAllocAndContext : sharedAllocContexts) { CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { upContexts = findUpContextsForVar( curAllocAndContext, new VarContextAndUp(loadBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { upContexts = findVarContextsFromAlloc( curAllocAndContext, loadBase); } for (ImmutableStack<Integer> upContext : upContexts) { p.prop(new VarAndContext(matchTgt, upContext)); } } } else { p.prop(new VarAndContext(matchTgt, EMPTY_CALLSTACK)); } // h.handleMatchSrc(matchSrc, intersection, // storeBase, // loadBase, varAndContext, checkGetfield); // if (h.terminate()) // return; } } } } return ret; } catch (CallSiteException e) { allocAndContextCache.remove(allocAndContext); throw e; } } protected int getMaxPasses() { return maxPasses; } protected void incrementNodesTraversed() { numNodesTraversed++; if (numNodesTraversed > maxNodesPerPass) { throw new TerminateEarlyException(); } } @SuppressWarnings("unused") protected boolean isRecursive(ImmutableStack<Integer> context, AssignEdge assignEdge) { boolean sameSCCAlready = callEdgeInSCC(assignEdge); if (sameSCCAlready) { return true; } Integer callSite = assignEdge.getCallSite(); if (context.contains(callSite)) { Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>(); int callSiteInd = 0; for (; callSiteInd < context.size() && !context.get(callSiteInd).equals(callSite); callSiteInd++) ; for (; callSiteInd < context.size(); callSiteInd++) { toBeCollapsed.add(csInfo.getInvokingMethod(context .get(callSiteInd))); } sccManager.makeSameSCC(toBeCollapsed); return true; } return false; } protected boolean isRecursiveCallSite(Integer callSite) { SootMethod invokingMethod = csInfo.getInvokingMethod(callSite); SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); return sccManager.inSameSCC(invokingMethod, invokedMethod); } @SuppressWarnings("unused") protected Set<VarNode> nodesPropagatedThrough(final VarNode source, final PointsToSetInternal allocs) { final Set<VarNode> marked = new HashSet<VarNode>(); final Stack<VarNode> worklist = new Stack<VarNode>(); Propagator<VarNode> p = new Propagator<VarNode>(marked, worklist); p.prop(source); while (!worklist.isEmpty()) { VarNode curNode = worklist.pop(); Node[] assignSources = pag.simpleInvLookup(curNode); for (int i = 0; i < assignSources.length; i++) { VarNode assignSrc = (VarNode) assignSources[i]; if (assignSrc.getP2Set().hasNonEmptyIntersection(allocs)) { p.prop(assignSrc); } } Set<VarNode> matchSources = vMatches.vMatchInvLookup(curNode); for (VarNode matchSrc : matchSources) { if (matchSrc.getP2Set().hasNonEmptyIntersection(allocs)) { p.prop(matchSrc); } } } return marked; } protected ImmutableStack<Integer> popRecursiveCallSites( ImmutableStack<Integer> context) { ImmutableStack<Integer> ret = context; while (!ret.isEmpty() && isRecursiveCallSite(ret.peek())) { ret = ret.pop(); } return ret; } protected void processIncomingEdges(IncomingEdgeHandler h, Stack<VarAndContext> worklist) { while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext varAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + varAndContext); } VarNode v = varAndContext.var; ImmutableStack<Integer> callingContext = varAndContext.context; Node[] newEdges = pag.allocInvLookup(v); for (int i = 0; i < newEdges.length; i++) { AllocNode allocNode = (AllocNode) newEdges[i]; h.handleAlloc(allocNode, varAndContext); if (h.terminate()) { return; } } Collection<AssignEdge> assigns = filterAssigns(v, callingContext, true, true); for (AssignEdge assignEdge : assigns) { VarNode src = assignEdge.getSrc(); // if (DEBUG) { // G.v().out.println("assign src " + src); // } if (h.shouldHandleSrc(src)) { ImmutableStack<Integer> newContext = callingContext; if (assignEdge.isParamEdge()) { if (!callingContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( callingContext.peek()) : assignEdge + " " + callingContext; newContext = callingContext.pop(); } else { newContext = popRecursiveCallSites(callingContext); } } // } else if (refiningCallSite) { // if (!fieldCheckHeuristic.aggressiveVirtCallRefine()) // { // // throw new CallSiteException(); // } // } } else if (assignEdge.isReturnEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(callingContext, assignEdge)) { // newContext = callingContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(callingContext, assignEdge); } if (assignEdge.isParamEdge()) { Integer callSite = assignEdge.getCallSite(); if (csInfo.isVirtCall(callSite) && !weirdCall(callSite)) { Set<SootMethod> targets = refineCallSite(callSite, newContext); if (DEBUG) { debugPrint(targets.toString()); } SootMethod targetMethod = ((LocalVarNode) assignEdge .getDst()).getMethod(); if (!targets.contains(targetMethod)) { if (DEBUG) { debugPrint("skipping call because of call graph"); } continue; } } } if (src instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } h.handleAssignSrc(new VarAndContext(src, newContext), varAndContext, assignEdge); if (h.terminate()) { return; } } } Set<VarNode> matchSources = vMatches.vMatchInvLookup(v); Node[] loads = pag.loadInvLookup(v); for (int i = 0; i < loads.length; i++) { FieldRefNode frNode = (FieldRefNode) loads[i]; final VarNode loadBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> getfield = new Pair<VarNode, // FieldRefNode>(v, frNode); for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) { final VarNode storeBase = store.getO2(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final VarNode matchSrc = store.getO1(); if (matchSources.contains(matchSrc)) { if (h.shouldHandleSrc(matchSrc)) { if (DEBUG) { debugPrint("match source " + matchSrc); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkGetfield = fieldCheckHeuristic .validateMatchesForField(field); h.handleMatchSrc(matchSrc, intersection, loadBase, storeBase, varAndContext, field, checkGetfield); if (h.terminate()) return; } } } } } } protected ImmutableStack<Integer> pushWithRecursionCheck( ImmutableStack<Integer> context, AssignEdge assignEdge) { boolean foundRecursion = callEdgeInSCC(assignEdge); if (!foundRecursion) { Integer callSite = assignEdge.getCallSite(); if (context.contains(callSite)) { foundRecursion = true; if (DEBUG) { debugPrint("RECURSION!!!"); } // TODO properly collapse recursive methods if (true) { throw new TerminateEarlyException(); } Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>(); int callSiteInd = 0; for (; callSiteInd < context.size() && !context.get(callSiteInd).equals(callSite); callSiteInd++) ; // int numToPop = 0; for (; callSiteInd < context.size(); callSiteInd++) { toBeCollapsed.add(csInfo.getInvokingMethod(context .get(callSiteInd))); // numToPop++; } sccManager.makeSameSCC(toBeCollapsed); // ImmutableStack<Integer> poppedContext = context; // for (int i = 0; i < numToPop; i++) { // poppedContext = poppedContext.pop(); // } // if (DEBUG) { // debugPrint("new stack " + poppedContext); // } // return poppedContext; } } if (foundRecursion) { ImmutableStack<Integer> popped = popRecursiveCallSites(context); if (DEBUG) { debugPrint("popped stack " + popped); } return popped; } else { return context.push(assignEdge.getCallSite()); } } protected boolean refineAlias(VarNode v1, VarNode v2, PointsToSetInternal intersection, HeuristicType heuristic) { if (refineAliasInternal(v1, v2, intersection, heuristic)) return true; if (refineAliasInternal(v2, v1, intersection, heuristic)) return true; return false; } protected boolean refineAliasInternal(VarNode v1, VarNode v2, PointsToSetInternal intersection, HeuristicType heuristic) { this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return false; } if (numPasses > maxPasses) { return false; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); boolean success = false; try { AllocAndContextSet allocAndContexts = findContextsForAllocs( new VarAndContext(v1, EMPTY_CALLSTACK), intersection); boolean emptyIntersection = true; for (AllocAndContext allocAndContext : allocAndContexts) { CallingContextSet upContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(v2, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); if (!upContexts.isEmpty()) { emptyIntersection = false; break; } } success = emptyIntersection; } catch (TerminateEarlyException e) { success = false; } if (success) { G.v().out.println("took " + numPasses + " passes"); return true; } else { if (!fieldCheckHeuristic.runNewPass()) { return false; } } } } protected Set<SootMethod> refineCallSite(Integer callSite, ImmutableStack<Integer> origContext) { CallSiteAndContext callSiteAndContext = new CallSiteAndContext( callSite, origContext); if (queriedCallSites.contains(callSiteAndContext)) { // if (DEBUG_VIRT) { // final SootMethod invokedMethod = // csInfo.getInvokedMethod(callSite); // final VarNode receiver = // csInfo.getReceiverForVirtCallSite(callSite); // debugPrint("call of " + invokedMethod + " on " + receiver + " " // + origContext + " goes to " // + callSiteToResolvedTargets.get(callSiteAndContext)); // } return callSiteToResolvedTargets.get(callSiteAndContext); } if (callGraphStack.contains(callSiteAndContext)) { return Collections.<SootMethod> emptySet(); } else { callGraphStack.push(callSiteAndContext); } final VarNode receiver = csInfo.getReceiverForVirtCallSite(callSite); final Type receiverType = receiver.getType(); final SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); final NumberedString methodSig = invokedMethod .getNumberedSubSignature(); final Set<SootMethod> allTargets = csInfo.getCallSiteTargets(callSite); if (!refineCallGraph) { callGraphStack.pop(); return allTargets; } if (DEBUG_VIRT) { debugPrint("refining call to " + invokedMethod + " on " + receiver + " " + origContext); } final HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final class Helper { void prop(VarAndContext varAndContext) { if (marked.add(varAndContext)) { worklist.push(varAndContext); } } } ; final Helper h = new Helper(); h.prop(new VarAndContext(receiver, origContext)); while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG_VIRT) { debugPrint("virt looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; // Set<SootMethod> curVarTargets = getCallTargets(curVar.getP2Set(), // methodSig, receiverType, allTargets); // if (curVarTargets.size() <= 1) { // for (SootMethod method : curVarTargets) { // callSiteToResolvedTargets.put(callSiteAndContext, method); // } // continue; // } Node[] newNodes = pag.allocInvLookup(curVar); for (int i = 0; i < newNodes.length; i++) { AllocNode allocNode = (AllocNode) newNodes[i]; for (SootMethod method : getCallTargetsForType(allocNode .getType(), methodSig, receiverType, allTargets)) { callSiteToResolvedTargets.put(callSiteAndContext, method); } } Collection<AssignEdge> assigns = filterAssigns(curVar, curContext, true, true); for (AssignEdge assignEdge : assigns) { VarNode src = assignEdge.getSrc(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isParamEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()); newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } else { callSiteToResolvedTargets.putAll(callSiteAndContext, allTargets); // if (DEBUG) { // debugPrint("giving up on virt"); // } continue; } } else if (assignEdge.isReturnEdge()) { // if (DEBUG) // G.v().out.println("entering call site " // + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge.getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } else if (src instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } h.prop(new VarAndContext(src, newContext)); } // TODO respect heuristic Set<VarNode> matchSources = vMatches.vMatchInvLookup(curVar); final boolean oneMatch = matchSources.size() == 1; Node[] loads = pag.loadInvLookup(curVar); for (int i = 0; i < loads.length; i++) { FieldRefNode frNode = (FieldRefNode) loads[i]; final VarNode loadBase = frNode.getBase(); SparkField field = frNode.getField(); for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) { final VarNode storeBase = store.getO2(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final VarNode matchSrc = store.getO1(); if (matchSources.contains(matchSrc)) { // optimize for common case of constructor init boolean skipMatch = false; if (oneMatch) { PointsToSetInternal matchSrcPTo = matchSrc .getP2Set(); Set<SootMethod> matchSrcCallTargets = getCallTargets( matchSrcPTo, methodSig, receiverType, allTargets); if (matchSrcCallTargets.size() <= 1) { skipMatch = true; for (SootMethod method : matchSrcCallTargets) { callSiteToResolvedTargets.put( callSiteAndContext, method); } } } if (!skipMatch) { final PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); AllocAndContextSet allocContexts = null; boolean oldRefining = refiningCallSite; int oldNesting = nesting; try { refiningCallSite = true; allocContexts = findContextsForAllocs( new VarAndContext(loadBase, curContext), intersection); } catch (CallSiteException e) { callSiteToResolvedTargets.putAll( callSiteAndContext, allTargets); continue; } finally { refiningCallSite = oldRefining; nesting = oldNesting; } for (AllocAndContext allocAndContext : allocContexts) { CallingContextSet matchSrcContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { VarAndContext newVarAndContext = new VarAndContext( matchSrc, matchSrcContext); h.prop(newVarAndContext); } } } } } } } if (DEBUG_VIRT) { debugPrint("call of " + invokedMethod + " on " + receiver + " " + origContext + " goes to " + callSiteToResolvedTargets.get(callSiteAndContext)); } callGraphStack.pop(); queriedCallSites.add(callSiteAndContext); return callSiteToResolvedTargets.get(callSiteAndContext); } protected boolean refineP2Set(VarAndContext varAndContext, final PointsToSetInternal badLocs) { nesting++; if (DEBUG) { debugPrint("refining " + varAndContext); } final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varAndContext); IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() { boolean success = true; @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { if (doPointsTo && pointsTo != null) { pointsTo.add(new AllocAndContext(allocNode, origVarAndContext.context)); } else { if (badLocs.contains(allocNode)) { success = false; } } } @Override public void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(loadBase, origVarAndContext.context), intersection); for (AllocAndContext allocAndContext : allocContexts) { if (DEBUG) { debugPrint("alloc and context " + allocAndContext); } CallingContextSet matchSrcContexts; if (fieldCheckHeuristic.validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { if (DEBUG) debugPrint("match source context " + matchSrcContext); VarAndContext newVarAndContext = new VarAndContext( matchSrc, matchSrcContext); p.prop(newVarAndContext); } } } Object getResult() { return Boolean.valueOf(success); } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { p.prop(newVarAndContext); } @Override boolean shouldHandleSrc(VarNode src) { if (doPointsTo) { return true; } else { return src.getP2Set().hasNonEmptyIntersection(badLocs); } } boolean terminate() { return !success; } }; processIncomingEdges(edgeHandler, worklist); nesting--; return (Boolean) edgeHandler.getResult(); } /* * (non-Javadoc) * * @see AAA.summary.Refiner#refineP2Set(soot.jimple.spark.pag.VarNode, * soot.jimple.spark.sets.PointsToSetInternal) */ protected boolean refineP2Set(VarNode v, PointsToSetInternal badLocs, HeuristicType heuristic) { // G.v().out.println(badLocs); this.doPointsTo = false; this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); try { numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return false; } if (numPasses > maxPasses) { return false; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); boolean success = false; try { success = refineP2Set( new VarAndContext(v, EMPTY_CALLSTACK), badLocs); } catch (TerminateEarlyException e) { success = false; } if (success) { return true; } else { if (!fieldCheckHeuristic.runNewPass()) { return false; } } } } finally { } } protected boolean weirdCall(Integer callSite) { SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); return SootUtil.isThreadStartMethod(invokedMethod) || SootUtil.isNewInstanceMethod(invokedMethod); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Context c, Local l) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Context c, Local l, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Local l, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(PointsToSet s, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) { throw new UnsupportedOperationException(); } /** * @return returns the (SPARK) pointer assignment graph */ public PAG getPAG() { return pag; } /** * @return <code>true</code> is caching is enabled */ public boolean usesCache() { return useCache; } /** * enables caching */ public void enableCache() { useCache = true; } /** * disables caching */ public void disableCache() { useCache = false; } /** * clears the cache */ public void clearCache() { reachingObjectsCache.clear(); } public boolean isRefineCallGraph() { return refineCallGraph; } public void setRefineCallGraph(boolean refineCallGraph) { this.refineCallGraph = refineCallGraph; } }
src/soot/jimple/spark/ondemand/DemandCSPointsTo.java
/* Soot - a J*va Optimization Framework * Copyright (C) 2007 Manu Sridharan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.spark.ondemand; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.AnySubType; import soot.ArrayType; import soot.Context; import soot.G; import soot.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.RefType; import soot.Scene; import soot.SootField; import soot.SootMethod; import soot.Type; import soot.jimple.spark.ondemand.genericutil.ArraySet; import soot.jimple.spark.ondemand.genericutil.HashSetMultiMap; import soot.jimple.spark.ondemand.genericutil.ImmutableStack; import soot.jimple.spark.ondemand.genericutil.Predicate; import soot.jimple.spark.ondemand.genericutil.Propagator; import soot.jimple.spark.ondemand.genericutil.Stack; import soot.jimple.spark.ondemand.pautil.AssignEdge; import soot.jimple.spark.ondemand.pautil.ContextSensitiveInfo; import soot.jimple.spark.ondemand.pautil.OTFMethodSCCManager; import soot.jimple.spark.ondemand.pautil.SootUtil; import soot.jimple.spark.ondemand.pautil.ValidMatches; import soot.jimple.spark.ondemand.pautil.SootUtil.FieldToEdgesMap; import soot.jimple.spark.pag.AllocNode; import soot.jimple.spark.pag.FieldRefNode; import soot.jimple.spark.pag.GlobalVarNode; import soot.jimple.spark.pag.LocalVarNode; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import soot.jimple.spark.pag.SparkField; import soot.jimple.spark.pag.VarNode; import soot.jimple.spark.sets.EmptyPointsToSet; import soot.jimple.spark.sets.HybridPointsToSet; import soot.jimple.spark.sets.P2SetVisitor; import soot.jimple.spark.sets.PointsToSetInternal; import soot.jimple.toolkits.callgraph.VirtualCalls; import soot.toolkits.scalar.Pair; import soot.util.NumberedString; /** * Tries to find imprecision in points-to sets from a previously run analysis. * Requires that all sub-results of previous analysis were cached. * * @author Manu Sridharan * */ public final class DemandCSPointsTo implements PointsToAnalysis { @SuppressWarnings("serial") protected static final class AllocAndContextCache extends HashMap<AllocAndContext, Map<VarNode, CallingContextSet>> { } protected static final class CallingContextSet extends ArraySet<ImmutableStack<Integer>> { } protected final static class CallSiteAndContext extends Pair<Integer, ImmutableStack<Integer>> { public CallSiteAndContext(Integer callSite, ImmutableStack<Integer> callingContext) { super(callSite, callingContext); } } protected static final class CallSiteToTargetsMap extends HashSetMultiMap<CallSiteAndContext, SootMethod> { } protected static abstract class IncomingEdgeHandler { public abstract void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext); public abstract void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine); abstract Object getResult(); abstract void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge); abstract boolean shouldHandleSrc(VarNode src); boolean terminate() { return false; } } protected static class VarAndContext { final ImmutableStack<Integer> context; final VarNode var; public VarAndContext(VarNode var, ImmutableStack<Integer> context) { assert var != null; assert context != null; this.var = var; this.context = context; } public boolean equals(Object o) { if (o != null && o.getClass() == VarAndContext.class) { VarAndContext other = (VarAndContext) o; return var.equals(other.var) && context.equals(other.context); } return false; } public int hashCode() { return var.hashCode() + context.hashCode(); } public String toString() { return var + " " + context; } } protected final static class VarContextAndUp extends VarAndContext { final ImmutableStack<Integer> upContext; public VarContextAndUp(VarNode var, ImmutableStack<Integer> context, ImmutableStack<Integer> upContext) { super(var, context); this.upContext = upContext; } public boolean equals(Object o) { if (o != null && o.getClass() == VarContextAndUp.class) { VarContextAndUp other = (VarContextAndUp) o; return var.equals(other.var) && context.equals(other.context) && upContext.equals(other.upContext); } return false; } public int hashCode() { return var.hashCode() + context.hashCode() + upContext.hashCode(); } public String toString() { return var + " " + context + " up " + upContext; } } protected static final boolean DEBUG = false; protected static final int DEBUG_NESTING = 15; protected static final int DEBUG_PASS = -1; protected static final boolean DEBUG_VIRT = DEBUG && true; protected static final int DEFAULT_MAX_PASSES = 10; protected static final int DEFAULT_MAX_TRAVERSAL = 75000; /** * if <code>true</code>, refine the pre-computed call graph */ private boolean refineCallGraph = true; protected static final ImmutableStack<Integer> EMPTY_CALLSTACK = ImmutableStack.<Integer> emptyStack(); /** * Make a default analysis. Assumes Spark has already run. * * @return */ public static DemandCSPointsTo makeDefault() { return makeWithBudget(DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES); } public static DemandCSPointsTo makeWithBudget(int maxTraversal, int maxPasses) { PAG pag = (PAG) Scene.v().getPointsToAnalysis(); ContextSensitiveInfo csInfo = new ContextSensitiveInfo(pag); return new DemandCSPointsTo(csInfo, pag, maxTraversal, maxPasses); } protected final AllocAndContextCache allocAndContextCache = new AllocAndContextCache(); protected Stack<Pair<Integer, ImmutableStack<Integer>>> callGraphStack = new Stack<Pair<Integer, ImmutableStack<Integer>>>(); protected final CallSiteToTargetsMap callSiteToResolvedTargets = new CallSiteToTargetsMap(); protected HashMap<List<Object>, Set<SootMethod>> callTargetsArgCache = new HashMap<List<Object>, Set<SootMethod>>(); protected final Stack<VarAndContext> contextForAllocsStack = new Stack<VarAndContext>(); protected Map<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>> contextsForAllocsCache = new HashMap<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>>(); protected final ContextSensitiveInfo csInfo; protected boolean doPointsTo; protected FieldCheckHeuristic fieldCheckHeuristic; protected final FieldToEdgesMap fieldToLoads; protected final FieldToEdgesMap fieldToStores; protected final int maxNodesPerPass; protected final int maxPasses; protected int nesting = 0; protected int numNodesTraversed; protected int numPasses = 0; protected final PAG pag; protected AllocAndContextSet pointsTo = null; protected final Set<CallSiteAndContext> queriedCallSites = new HashSet<CallSiteAndContext>(); protected int recursionDepth = -1; protected boolean refiningCallSite = false; protected OTFMethodSCCManager sccManager; protected Map<VarContextAndUp, Map<AllocAndContext, CallingContextSet>> upContextCache = new HashMap<VarContextAndUp, Map<AllocAndContext, CallingContextSet>>(); protected final ValidMatches vMatches; protected Map<Local,PointsToSet> reachingObjectsCache; protected boolean useCache; public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag) { this(csInfo, pag, DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES); } public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag, int maxTraversal, int maxPasses) { this.csInfo = csInfo; this.pag = pag; this.fieldToStores = SootUtil.storesOnField(pag); this.fieldToLoads = SootUtil.loadsOnField(pag); this.vMatches = new ValidMatches(pag, fieldToStores); this.maxPasses = maxPasses; this.maxNodesPerPass = maxTraversal / maxPasses; this.fieldCheckHeuristic = HeuristicType.getHeuristic( HeuristicType.INCR, pag.getTypeManager(), getMaxPasses()); this.reachingObjectsCache = new HashMap<Local, PointsToSet>(); this.useCache = true; } /** * {@inheritDoc} */ public PointsToSet reachingObjects(Local l) { PointsToSet result = reachingObjectsCache.get(l); if(result==null) { result = computeReachingObjects(l); if(useCache) { reachingObjectsCache.put(l, result); } } return result; } /** * Computes the possibly refined set of reaching objects for l. */ protected PointsToSet computeReachingObjects(Local l) { PointsToSet result; VarNode v = pag.findLocalVarNode(l); if (v == null) { return EmptyPointsToSet.v(); } // must reset the refinement heuristic for each query this.fieldCheckHeuristic = HeuristicType.getHeuristic( HeuristicType.INCR, pag.getTypeManager(), getMaxPasses()); doPointsTo = true; numPasses = 0; PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v); if(contextSensitiveResult == null ) { result = new WrappedPointsToSet(v.getP2Set()); } else { result = contextSensitiveResult; } return result; } /** * Computes the refined set of reaching objects for l. * Returns <code>null</code> if refinement failed. */ protected PointsToSet computeRefinedReachingObjects(VarNode v) { PointsToSet contextSensitiveResult = null; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { break; } if (numPasses > maxPasses) { break; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); pointsTo = new AllocAndContextSet(); try { refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null); contextSensitiveResult = pointsTo; } catch (TerminateEarlyException e) { } if (!fieldCheckHeuristic.runNewPass()) { break; } } return contextSensitiveResult; } protected boolean callEdgeInSCC(AssignEdge assignEdge) { boolean sameSCCAlready = false; assert assignEdge.isCallEdge(); // assert assignEdge.getSrc() instanceof LocalVarNode : // assignEdge.getSrc() + " not LocalVarNode"; if (!(assignEdge.getSrc() instanceof LocalVarNode) || !(assignEdge.getDst() instanceof LocalVarNode)) { return false; } LocalVarNode src = (LocalVarNode) assignEdge.getSrc(); LocalVarNode dst = (LocalVarNode) assignEdge.getDst(); if (sccManager.inSameSCC(src.getMethod(), dst.getMethod())) { sameSCCAlready = true; } return sameSCCAlready; } protected CallingContextSet checkAllocAndContextCache( AllocAndContext allocAndContext, VarNode targetVar) { if (allocAndContextCache.containsKey(allocAndContext)) { Map<VarNode, CallingContextSet> m = allocAndContextCache .get(allocAndContext); if (m.containsKey(targetVar)) { return m.get(targetVar); } } else { allocAndContextCache.put(allocAndContext, new HashMap<VarNode, CallingContextSet>()); } return null; } protected PointsToSetInternal checkContextsForAllocsCache( VarAndContext varAndContext, AllocAndContextSet ret, PointsToSetInternal locs) { PointsToSetInternal retSet = null; if (contextsForAllocsCache.containsKey(varAndContext)) { for (AllocAndContext allocAndContext : contextsForAllocsCache.get( varAndContext).getO2()) { if (locs.contains(allocAndContext.alloc)) { ret.add(allocAndContext); } } final PointsToSetInternal oldLocs = contextsForAllocsCache.get( varAndContext).getO1(); final PointsToSetInternal tmpSet = new HybridPointsToSet(locs .getType(), pag); locs.forall(new P2SetVisitor() { @Override public void visit(Node n) { if (!oldLocs.contains(n)) { tmpSet.add(n); } } }); retSet = tmpSet; oldLocs.addAll(tmpSet, null); } else { PointsToSetInternal storedSet = new HybridPointsToSet(locs .getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache.put(varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, new AllocAndContextSet())); retSet = locs; } return retSet; } /** * check the computed points-to set of a variable against some predicate * * @param v * the variable * @param heuristic * how to refine match edges * @param p2setPred * the predicate on the points-to set * @return true if the p2setPred holds for the computed points-to set, or if * a points-to set cannot be computed in the budget; false otherwise */ protected boolean checkP2Set(VarNode v, HeuristicType heuristic, Predicate<Set<AllocAndContext>> p2setPred) { doPointsTo = true; // DEBUG = v.getNumber() == 150; this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return true; } if (numPasses > maxPasses) { return true; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); pointsTo = new AllocAndContextSet(); boolean success = false; try { success = refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null); } catch (TerminateEarlyException e) { success = false; } if (success) { if (p2setPred.test(pointsTo)) { return false; } } else { if (!fieldCheckHeuristic.runNewPass()) { return true; } } } } // protected boolean upContextsSane(CallingContextSet ret, AllocAndContext // allocAndContext, VarContextAndUp varContextAndUp) { // for (ImmutableStack<Integer> context : ret) { // ImmutableStack<Integer> fixedContext = fixUpContext(context, // allocAndContext, varContextAndUp); // if (!context.equals(fixedContext)) { // return false; // } // } // return true; // } // // protected CallingContextSet fixAllUpContexts(CallingContextSet contexts, // AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) { // if (DEBUG) { // debugPrint("fixing up contexts"); // } // CallingContextSet ret = new CallingContextSet(); // for (ImmutableStack<Integer> context : contexts) { // ret.add(fixUpContext(context, allocAndContext, varContextAndUp)); // } // return ret; // } // // protected ImmutableStack<Integer> fixUpContext(ImmutableStack<Integer> // context, AllocAndContext allocAndContext, VarContextAndUp // varContextAndUp) { // // return null; // } protected CallingContextSet checkUpContextCache( VarContextAndUp varContextAndUp, AllocAndContext allocAndContext) { if (upContextCache.containsKey(varContextAndUp)) { Map<AllocAndContext, CallingContextSet> allocAndContextMap = upContextCache .get(varContextAndUp); if (allocAndContextMap.containsKey(allocAndContext)) { return allocAndContextMap.get(allocAndContext); } } else { upContextCache.put(varContextAndUp, new HashMap<AllocAndContext, CallingContextSet>()); } return null; } protected void clearState() { allocAndContextCache.clear(); callGraphStack.clear(); callSiteToResolvedTargets.clear(); queriedCallSites.clear(); contextsForAllocsCache.clear(); contextForAllocsStack.clear(); upContextCache.clear(); callTargetsArgCache.clear(); sccManager = new OTFMethodSCCManager(); numNodesTraversed = 0; nesting = 0; recursionDepth = -1; } /** * compute a flows-to set for an allocation site. for now, we use a simple * refinement strategy; just refine as much as possible, maintaining the * smallest set of flows-to vars * * @param alloc * @param heuristic * @return */ protected Set<VarNode> computeFlowsTo(AllocNode alloc, HeuristicType heuristic) { this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; Set<VarNode> smallest = null; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return smallest; } if (numPasses > maxPasses) { return smallest; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); Set<VarNode> result = null; try { result = getFlowsToHelper(new AllocAndContext(alloc, EMPTY_CALLSTACK)); } catch (TerminateEarlyException e) { } if (result != null) { if (smallest == null || result.size() < smallest.size()) { smallest = result; } } if (!fieldCheckHeuristic.runNewPass()) { return smallest; } } } protected void debugPrint(String str) { if (nesting <= DEBUG_NESTING) { if (DEBUG_PASS == -1 || DEBUG_PASS == numPasses) { G.v().out.println(":" + nesting + " " + str); } } } /* * (non-Javadoc) * * @see AAA.summary.Refiner#dumpPathForBadLoc(soot.jimple.spark.pag.VarNode, * soot.jimple.spark.pag.AllocNode) */ protected void dumpPathForLoc(VarNode v, final AllocNode badLoc, String filePrefix) { final HashSet<VarNode> visited = new HashSet<VarNode>(); final DotPointerGraph dotGraph = new DotPointerGraph(); final class Helper { boolean handle(VarNode curNode) { assert curNode.getP2Set().contains(badLoc); visited.add(curNode); Node[] newEdges = pag.allocInvLookup(curNode); for (int i = 0; i < newEdges.length; i++) { AllocNode alloc = (AllocNode) newEdges[i]; if (alloc.equals(badLoc)) { dotGraph.addNew(alloc, curNode); return true; } } for (AssignEdge assignEdge : csInfo.getAssignEdges(curNode)) { VarNode other = assignEdge.getSrc(); if (other.getP2Set().contains(badLoc) && !visited.contains(other) && handle(other)) { if (assignEdge.isCallEdge()) { dotGraph.addCall(other, curNode, assignEdge .getCallSite()); } else { dotGraph.addAssign(other, curNode); } return true; } } Node[] loadEdges = pag.loadInvLookup(curNode); for (int i = 0; i < loadEdges.length; i++) { FieldRefNode frNode = (FieldRefNode) loadEdges[i]; SparkField field = frNode.getField(); VarNode base = frNode.getBase(); PointsToSetInternal baseP2Set = base.getP2Set(); for (Pair<VarNode, VarNode> store : fieldToStores .get(field)) { if (store.getO2().getP2Set().hasNonEmptyIntersection( baseP2Set)) { VarNode matchSrc = store.getO1(); if (matchSrc.getP2Set().contains(badLoc) && !visited.contains(matchSrc) && handle(matchSrc)) { dotGraph.addMatch(matchSrc, curNode); return true; } } } } return false; } } Helper h = new Helper(); h.handle(v); // G.v().out.println(dotGraph.numEdges() + " edges on path"); dotGraph.dump("tmp/" + filePrefix + v.getNumber() + "_" + badLoc.getNumber() + ".dot"); } protected Collection<AssignEdge> filterAssigns(final VarNode v, final ImmutableStack<Integer> callingContext, boolean forward, boolean refineVirtCalls) { Set<AssignEdge> assigns = forward ? csInfo.getAssignEdges(v) : csInfo .getAssignBarEdges(v); Collection<AssignEdge> realAssigns; boolean exitNode = forward ? SootUtil.isParamNode(v) : SootUtil .isRetNode(v); final boolean backward = !forward; if (exitNode && !callingContext.isEmpty()) { Integer topCallSite = callingContext.peek(); realAssigns = new ArrayList<AssignEdge>(); for (AssignEdge assignEdge : assigns) { assert (forward && assignEdge.isParamEdge()) || (backward && assignEdge.isReturnEdge()) : assignEdge; Integer assignEdgeCallSite = assignEdge.getCallSite(); assert csInfo.getCallSiteTargets(assignEdgeCallSite).contains( ((LocalVarNode) v).getMethod()) : assignEdge; if (topCallSite.equals(assignEdgeCallSite) || callEdgeInSCC(assignEdge)) { realAssigns.add(assignEdge); } } // assert realAssigns.size() == 1; } else { if (assigns.size() > 1) { realAssigns = new ArrayList<AssignEdge>(); for (AssignEdge assignEdge : assigns) { boolean enteringCall = forward ? assignEdge.isReturnEdge() : assignEdge.isParamEdge(); if (enteringCall) { Integer callSite = assignEdge.getCallSite(); if (csInfo.isVirtCall(callSite) && refineVirtCalls) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), callingContext); LocalVarNode nodeInTargetMethod = forward ? (LocalVarNode) assignEdge .getSrc() : (LocalVarNode) assignEdge.getDst(); if (targets .contains(nodeInTargetMethod.getMethod())) { realAssigns.add(assignEdge); } } else { realAssigns.add(assignEdge); } } else { realAssigns.add(assignEdge); } } } else { realAssigns = assigns; } } return realAssigns; } protected AllocAndContextSet findContextsForAllocs( final VarAndContext varAndContext, PointsToSetInternal locs) { if (contextForAllocsStack.contains(varAndContext)) { // recursion; check depth // we're fine for x = x.next int oldIndex = contextForAllocsStack.indexOf(varAndContext); if (oldIndex != contextForAllocsStack.size() - 1) { if (recursionDepth == -1) { recursionDepth = oldIndex + 1; if (DEBUG) { debugPrint("RECURSION depth = " + recursionDepth); } } else if (contextForAllocsStack.size() - oldIndex > 5) { // just give up throw new TerminateEarlyException(); } } } contextForAllocsStack.push(varAndContext); final AllocAndContextSet ret = new AllocAndContextSet(); final PointsToSetInternal realLocs = checkContextsForAllocsCache( varAndContext, ret, locs); if (realLocs.isEmpty()) { if (DEBUG) { debugPrint("cached result " + ret); } contextForAllocsStack.pop(); return ret; } nesting++; if (DEBUG) { debugPrint("finding alloc contexts for " + varAndContext); } try { final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varAndContext); IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() { @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { if (realLocs.contains(allocNode)) { if (DEBUG) { debugPrint("found alloc " + allocNode); } ret.add(new AllocAndContext(allocNode, origVarAndContext.context)); } } @Override public void handleMatchSrc(final VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { if (DEBUG) { debugPrint("handling src " + matchSrc); debugPrint("intersection " + intersection); } if (!refine) { p.prop(new VarAndContext(matchSrc, EMPTY_CALLSTACK)); return; } AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(loadBase, origVarAndContext.context), intersection); if (DEBUG) { debugPrint("alloc contexts " + allocContexts); } for (AllocAndContext allocAndContext : allocContexts) { if (DEBUG) { debugPrint("alloc and context " + allocAndContext); } CallingContextSet matchSrcContexts; if (fieldCheckHeuristic.validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp( storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { // ret // .add(new Pair<AllocNode, // ImmutableStack<Integer>>( // (AllocNode) n, // matchSrcContext)); // ret.addAll(findContextsForAllocs(matchSrc, // matchSrcContext, locs)); p .prop(new VarAndContext(matchSrc, matchSrcContext)); } } } @Override Object getResult() { return ret; } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { p.prop(newVarAndContext); } @Override boolean shouldHandleSrc(VarNode src) { return realLocs.hasNonEmptyIntersection(src.getP2Set()); } }; processIncomingEdges(edgeHandler, worklist); // update the cache if (recursionDepth != -1) { // if we're beyond recursion, don't cache anything if (contextForAllocsStack.size() > recursionDepth) { if (DEBUG) { debugPrint("REMOVING " + varAndContext); debugPrint(contextForAllocsStack.toString()); } contextsForAllocsCache.remove(varAndContext); } else { assert contextForAllocsStack.size() == recursionDepth : recursionDepth + " " + contextForAllocsStack; recursionDepth = -1; if (contextsForAllocsCache.containsKey(varAndContext)) { contextsForAllocsCache.get(varAndContext).getO2() .addAll(ret); } else { PointsToSetInternal storedSet = new HybridPointsToSet( locs.getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache .put( varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, ret)); } } } else { if (contextsForAllocsCache.containsKey(varAndContext)) { contextsForAllocsCache.get(varAndContext).getO2().addAll( ret); } else { PointsToSetInternal storedSet = new HybridPointsToSet(locs .getType(), pag); storedSet.addAll(locs, null); contextsForAllocsCache.put(varAndContext, new Pair<PointsToSetInternal, AllocAndContextSet>( storedSet, ret)); } } nesting--; return ret; } catch (CallSiteException e) { contextsForAllocsCache.remove(varAndContext); throw e; } finally { contextForAllocsStack.pop(); } } protected CallingContextSet findUpContextsForVar( AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) { final AllocNode alloc = allocAndContext.alloc; final ImmutableStack<Integer> allocContext = allocAndContext.context; CallingContextSet tmpSet = checkUpContextCache(varContextAndUp, allocAndContext); if (tmpSet != null) { return tmpSet; } final CallingContextSet ret = new CallingContextSet(); upContextCache.get(varContextAndUp).put(allocAndContext, ret); nesting++; if (DEBUG) { debugPrint("finding up context for " + varContextAndUp + " to " + alloc + " " + allocContext); } try { final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varContextAndUp); class UpContextEdgeHandler extends IncomingEdgeHandler { @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; if (allocNode == alloc) { if (allocContext.topMatches(contextAndUp.context)) { ImmutableStack<Integer> reverse = contextAndUp.upContext .reverse(); ImmutableStack<Integer> toAdd = allocContext .popAll(contextAndUp.context).pushAll( reverse); if (DEBUG) { debugPrint("found up context " + toAdd); } ret.add(toAdd); } else if (contextAndUp.context .topMatches(allocContext)) { ImmutableStack<Integer> toAdd = contextAndUp.upContext .reverse(); if (DEBUG) { debugPrint("found up context " + toAdd); } ret.add(toAdd); } } } @Override public void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; if (DEBUG) { debugPrint("CHECKING " + alloc); } PointsToSetInternal tmp = new HybridPointsToSet(alloc .getType(), pag); tmp.add(alloc); AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(matchSrc, EMPTY_CALLSTACK), tmp); // Set allocContexts = Collections.singleton(new Object()); if (!refine) { if (!allocContexts.isEmpty()) { ret.add(contextAndUp.upContext.reverse()); } } else { if (!allocContexts.isEmpty()) { for (AllocAndContext t : allocContexts) { ImmutableStack<Integer> discoveredAllocContext = t.context; if (!allocContext .topMatches(discoveredAllocContext)) { continue; } ImmutableStack<Integer> trueAllocContext = allocContext .popAll(discoveredAllocContext); AllocAndContextSet allocAndContexts = findContextsForAllocs( new VarAndContext(storeBase, trueAllocContext), intersection); for (AllocAndContext allocAndContext : allocAndContexts) { // if (DEBUG) // G.v().out.println("alloc context " // + newAllocContext); // CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { ret .addAll(findUpContextsForVar( allocAndContext, new VarContextAndUp( loadBase, contextAndUp.context, contextAndUp.upContext))); } else { CallingContextSet tmpContexts = findVarContextsFromAlloc( allocAndContext, loadBase); // upContexts = new CallingContextSet(); for (ImmutableStack<Integer> tmpContext : tmpContexts) { if (tmpContext .topMatches(contextAndUp.context)) { ImmutableStack<Integer> reverse = contextAndUp.upContext .reverse(); ImmutableStack<Integer> toAdd = tmpContext .popAll( contextAndUp.context) .pushAll(reverse); ret.add(toAdd); } } } } } } } } @Override Object getResult() { return ret; } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext; ImmutableStack<Integer> upContext = contextAndUp.upContext; ImmutableStack<Integer> newUpContext = upContext; if (assignEdge.isParamEdge() && contextAndUp.context.isEmpty()) { if (upContext.size() < ImmutableStack.getMaxSize()) { newUpContext = pushWithRecursionCheck(upContext, assignEdge); } ; } p.prop(new VarContextAndUp(newVarAndContext.var, newVarAndContext.context, newUpContext)); } @Override boolean shouldHandleSrc(VarNode src) { if (src instanceof GlobalVarNode) { // TODO properly handle case of global here; rare // but possible // reachedGlobal = true; // // for now, just give up throw new TerminateEarlyException(); } return src.getP2Set().contains(alloc); } } ; UpContextEdgeHandler edgeHandler = new UpContextEdgeHandler(); processIncomingEdges(edgeHandler, worklist); nesting--; // if (edgeHandler.reachedGlobal) { // return fixAllUpContexts(ret, allocAndContext, varContextAndUp); // } else { // assert upContextsSane(ret, allocAndContext, varContextAndUp); // return ret; // } return ret; } catch (CallSiteException e) { upContextCache.remove(varContextAndUp); throw e; } } protected CallingContextSet findVarContextsFromAlloc( AllocAndContext allocAndContext, VarNode targetVar) { CallingContextSet tmpSet = checkAllocAndContextCache(allocAndContext, targetVar); if (tmpSet != null) { return tmpSet; } CallingContextSet ret = new CallingContextSet(); allocAndContextCache.get(allocAndContext).put(targetVar, ret); try { HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); Stack<VarAndContext> worklist = new Stack<VarAndContext>(); Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked, worklist); AllocNode alloc = allocAndContext.alloc; ImmutableStack<Integer> allocContext = allocAndContext.context; Node[] newBarNodes = pag.allocLookup(alloc); for (int i = 0; i < newBarNodes.length; i++) { VarNode v = (VarNode) newBarNodes[i]; p.prop(new VarAndContext(v, allocContext)); } while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; if (curVar == targetVar) { ret.add(curContext); } // assign Collection<AssignEdge> assignEdges = filterAssigns(curVar, curContext, false, true); for (AssignEdge assignEdge : assignEdges) { VarNode dst = assignEdge.getDst(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isReturnEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()) : assignEdge + " " + curContext; newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } } else if (assignEdge.isParamEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } if (assignEdge.isReturnEdge() && curContext.isEmpty() && csInfo.isVirtCall(assignEdge.getCallSite())) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), newContext); if (!targets.contains(((LocalVarNode) assignEdge .getDst()).getMethod())) { continue; } } if (dst instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } p.prop(new VarAndContext(dst, newContext)); } // putfield_bars Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar); Node[] pfTargets = pag.storeLookup(curVar); for (int i = 0; i < pfTargets.length; i++) { FieldRefNode frNode = (FieldRefNode) pfTargets[i]; final VarNode storeBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode, // FieldRefNode>(curVar, frNode); for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) { final VarNode loadBase = load.getO2(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final VarNode matchTgt = load.getO1(); if (matchTargets.contains(matchTgt)) { if (DEBUG) { debugPrint("match source " + matchTgt); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkField = fieldCheckHeuristic .validateMatchesForField(field); if (checkField) { AllocAndContextSet sharedAllocContexts = findContextsForAllocs( new VarAndContext(storeBase, curContext), intersection); for (AllocAndContext curAllocAndContext : sharedAllocContexts) { CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { upContexts = findUpContextsForVar( curAllocAndContext, new VarContextAndUp(loadBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { upContexts = findVarContextsFromAlloc( curAllocAndContext, loadBase); } for (ImmutableStack<Integer> upContext : upContexts) { p.prop(new VarAndContext(matchTgt, upContext)); } } } else { p.prop(new VarAndContext(matchTgt, EMPTY_CALLSTACK)); } // h.handleMatchSrc(matchSrc, intersection, // storeBase, // loadBase, varAndContext, checkGetfield); // if (h.terminate()) // return; } } } } return ret; } catch (CallSiteException e) { allocAndContextCache.remove(allocAndContext); throw e; } } @SuppressWarnings("unchecked") protected Set<SootMethod> getCallTargets(PointsToSetInternal p2Set, NumberedString methodStr, Type receiverType, Set<SootMethod> possibleTargets) { List<Object> args = Arrays.asList(p2Set, methodStr, receiverType, possibleTargets); if (callTargetsArgCache.containsKey(args)) { return callTargetsArgCache.get(args); } Set<Type> types = p2Set.possibleTypes(); Set<SootMethod> ret = new HashSet<SootMethod>(); for (Type type : types) { ret.addAll(getCallTargetsForType(type, methodStr, receiverType, possibleTargets)); } callTargetsArgCache.put(args, ret); return ret; } protected Set<SootMethod> getCallTargetsForType(Type type, NumberedString methodStr, Type receiverType, Set<SootMethod> possibleTargets) { if (!pag.getTypeManager().castNeverFails(type, receiverType)) return Collections.<SootMethod> emptySet(); if (type instanceof AnySubType) { AnySubType any = (AnySubType) type; RefType refType = any.getBase(); if (pag.getTypeManager().getFastHierarchy().canStoreType( receiverType, refType) || pag.getTypeManager().getFastHierarchy().canStoreType( refType, receiverType)) { return possibleTargets; } else { return Collections.<SootMethod> emptySet(); } } if (type instanceof ArrayType) { // we'll invoke the java.lang.Object method in this // case // Assert.chk(varNodeType.toString().equals("java.lang.Object")); type = Scene.v().getSootClass("java.lang.Object").getType(); } RefType refType = (RefType) type; SootMethod targetMethod = null; targetMethod = VirtualCalls.v().resolveNonSpecial(refType, methodStr); return Collections.<SootMethod> singleton(targetMethod); } protected Set<VarNode> getFlowsToHelper(AllocAndContext allocAndContext) { Set<VarNode> ret = new ArraySet<VarNode>(); try { HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); Stack<VarAndContext> worklist = new Stack<VarAndContext>(); Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked, worklist); AllocNode alloc = allocAndContext.alloc; ImmutableStack<Integer> allocContext = allocAndContext.context; Node[] newBarNodes = pag.allocLookup(alloc); for (int i = 0; i < newBarNodes.length; i++) { VarNode v = (VarNode) newBarNodes[i]; ret.add(v); p.prop(new VarAndContext(v, allocContext)); } while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; ret.add(curVar); // assign Collection<AssignEdge> assignEdges = filterAssigns(curVar, curContext, false, true); for (AssignEdge assignEdge : assignEdges) { VarNode dst = assignEdge.getDst(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isReturnEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()) : assignEdge + " " + curContext; newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } } else if (assignEdge.isParamEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } if (assignEdge.isReturnEdge() && curContext.isEmpty() && csInfo.isVirtCall(assignEdge.getCallSite())) { Set<SootMethod> targets = refineCallSite(assignEdge .getCallSite(), newContext); if (!targets.contains(((LocalVarNode) assignEdge .getDst()).getMethod())) { continue; } } if (dst instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } p.prop(new VarAndContext(dst, newContext)); } // putfield_bars Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar); Node[] pfTargets = pag.storeLookup(curVar); for (int i = 0; i < pfTargets.length; i++) { FieldRefNode frNode = (FieldRefNode) pfTargets[i]; final VarNode storeBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode, // FieldRefNode>(curVar, frNode); for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) { final VarNode loadBase = load.getO2(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final VarNode matchTgt = load.getO1(); if (matchTargets.contains(matchTgt)) { if (DEBUG) { debugPrint("match source " + matchTgt); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkField = fieldCheckHeuristic .validateMatchesForField(field); if (checkField) { AllocAndContextSet sharedAllocContexts = findContextsForAllocs( new VarAndContext(storeBase, curContext), intersection); for (AllocAndContext curAllocAndContext : sharedAllocContexts) { CallingContextSet upContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { upContexts = findUpContextsForVar( curAllocAndContext, new VarContextAndUp(loadBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { upContexts = findVarContextsFromAlloc( curAllocAndContext, loadBase); } for (ImmutableStack<Integer> upContext : upContexts) { p.prop(new VarAndContext(matchTgt, upContext)); } } } else { p.prop(new VarAndContext(matchTgt, EMPTY_CALLSTACK)); } // h.handleMatchSrc(matchSrc, intersection, // storeBase, // loadBase, varAndContext, checkGetfield); // if (h.terminate()) // return; } } } } return ret; } catch (CallSiteException e) { allocAndContextCache.remove(allocAndContext); throw e; } } protected int getMaxPasses() { return maxPasses; } protected void incrementNodesTraversed() { numNodesTraversed++; if (numNodesTraversed > maxNodesPerPass) { throw new TerminateEarlyException(); } } @SuppressWarnings("unused") protected boolean isRecursive(ImmutableStack<Integer> context, AssignEdge assignEdge) { boolean sameSCCAlready = callEdgeInSCC(assignEdge); if (sameSCCAlready) { return true; } Integer callSite = assignEdge.getCallSite(); if (context.contains(callSite)) { Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>(); int callSiteInd = 0; for (; callSiteInd < context.size() && !context.get(callSiteInd).equals(callSite); callSiteInd++) ; for (; callSiteInd < context.size(); callSiteInd++) { toBeCollapsed.add(csInfo.getInvokingMethod(context .get(callSiteInd))); } sccManager.makeSameSCC(toBeCollapsed); return true; } return false; } protected boolean isRecursiveCallSite(Integer callSite) { SootMethod invokingMethod = csInfo.getInvokingMethod(callSite); SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); return sccManager.inSameSCC(invokingMethod, invokedMethod); } @SuppressWarnings("unused") protected Set<VarNode> nodesPropagatedThrough(final VarNode source, final PointsToSetInternal allocs) { final Set<VarNode> marked = new HashSet<VarNode>(); final Stack<VarNode> worklist = new Stack<VarNode>(); Propagator<VarNode> p = new Propagator<VarNode>(marked, worklist); p.prop(source); while (!worklist.isEmpty()) { VarNode curNode = worklist.pop(); Node[] assignSources = pag.simpleInvLookup(curNode); for (int i = 0; i < assignSources.length; i++) { VarNode assignSrc = (VarNode) assignSources[i]; if (assignSrc.getP2Set().hasNonEmptyIntersection(allocs)) { p.prop(assignSrc); } } Set<VarNode> matchSources = vMatches.vMatchInvLookup(curNode); for (VarNode matchSrc : matchSources) { if (matchSrc.getP2Set().hasNonEmptyIntersection(allocs)) { p.prop(matchSrc); } } } return marked; } protected ImmutableStack<Integer> popRecursiveCallSites( ImmutableStack<Integer> context) { ImmutableStack<Integer> ret = context; while (!ret.isEmpty() && isRecursiveCallSite(ret.peek())) { ret = ret.pop(); } return ret; } protected void processIncomingEdges(IncomingEdgeHandler h, Stack<VarAndContext> worklist) { while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext varAndContext = worklist.pop(); if (DEBUG) { debugPrint("looking at " + varAndContext); } VarNode v = varAndContext.var; ImmutableStack<Integer> callingContext = varAndContext.context; Node[] newEdges = pag.allocInvLookup(v); for (int i = 0; i < newEdges.length; i++) { AllocNode allocNode = (AllocNode) newEdges[i]; h.handleAlloc(allocNode, varAndContext); if (h.terminate()) { return; } } Collection<AssignEdge> assigns = filterAssigns(v, callingContext, true, true); for (AssignEdge assignEdge : assigns) { VarNode src = assignEdge.getSrc(); // if (DEBUG) { // G.v().out.println("assign src " + src); // } if (h.shouldHandleSrc(src)) { ImmutableStack<Integer> newContext = callingContext; if (assignEdge.isParamEdge()) { if (!callingContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( callingContext.peek()) : assignEdge + " " + callingContext; newContext = callingContext.pop(); } else { newContext = popRecursiveCallSites(callingContext); } } // } else if (refiningCallSite) { // if (!fieldCheckHeuristic.aggressiveVirtCallRefine()) // { // // throw new CallSiteException(); // } // } } else if (assignEdge.isReturnEdge()) { if (DEBUG) debugPrint("entering call site " + assignEdge.getCallSite()); // if (!isRecursive(callingContext, assignEdge)) { // newContext = callingContext.push(assignEdge // .getCallSite()); // } newContext = pushWithRecursionCheck(callingContext, assignEdge); } if (assignEdge.isParamEdge()) { Integer callSite = assignEdge.getCallSite(); if (csInfo.isVirtCall(callSite) && !weirdCall(callSite)) { Set<SootMethod> targets = refineCallSite(callSite, newContext); if (DEBUG) { debugPrint(targets.toString()); } SootMethod targetMethod = ((LocalVarNode) assignEdge .getDst()).getMethod(); if (!targets.contains(targetMethod)) { if (DEBUG) { debugPrint("skipping call because of call graph"); } continue; } } } if (src instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } h.handleAssignSrc(new VarAndContext(src, newContext), varAndContext, assignEdge); if (h.terminate()) { return; } } } Set<VarNode> matchSources = vMatches.vMatchInvLookup(v); Node[] loads = pag.loadInvLookup(v); for (int i = 0; i < loads.length; i++) { FieldRefNode frNode = (FieldRefNode) loads[i]; final VarNode loadBase = frNode.getBase(); SparkField field = frNode.getField(); // Pair<VarNode, FieldRefNode> getfield = new Pair<VarNode, // FieldRefNode>(v, frNode); for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) { final VarNode storeBase = store.getO2(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final VarNode matchSrc = store.getO1(); if (matchSources.contains(matchSrc)) { if (h.shouldHandleSrc(matchSrc)) { if (DEBUG) { debugPrint("match source " + matchSrc); } PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); boolean checkGetfield = fieldCheckHeuristic .validateMatchesForField(field); h.handleMatchSrc(matchSrc, intersection, loadBase, storeBase, varAndContext, field, checkGetfield); if (h.terminate()) return; } } } } } } protected ImmutableStack<Integer> pushWithRecursionCheck( ImmutableStack<Integer> context, AssignEdge assignEdge) { boolean foundRecursion = callEdgeInSCC(assignEdge); if (!foundRecursion) { Integer callSite = assignEdge.getCallSite(); if (context.contains(callSite)) { foundRecursion = true; if (DEBUG) { debugPrint("RECURSION!!!"); } // TODO properly collapse recursive methods if (true) { throw new TerminateEarlyException(); } Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>(); int callSiteInd = 0; for (; callSiteInd < context.size() && !context.get(callSiteInd).equals(callSite); callSiteInd++) ; // int numToPop = 0; for (; callSiteInd < context.size(); callSiteInd++) { toBeCollapsed.add(csInfo.getInvokingMethod(context .get(callSiteInd))); // numToPop++; } sccManager.makeSameSCC(toBeCollapsed); // ImmutableStack<Integer> poppedContext = context; // for (int i = 0; i < numToPop; i++) { // poppedContext = poppedContext.pop(); // } // if (DEBUG) { // debugPrint("new stack " + poppedContext); // } // return poppedContext; } } if (foundRecursion) { ImmutableStack<Integer> popped = popRecursiveCallSites(context); if (DEBUG) { debugPrint("popped stack " + popped); } return popped; } else { return context.push(assignEdge.getCallSite()); } } protected boolean refineAlias(VarNode v1, VarNode v2, PointsToSetInternal intersection, HeuristicType heuristic) { if (refineAliasInternal(v1, v2, intersection, heuristic)) return true; if (refineAliasInternal(v2, v1, intersection, heuristic)) return true; return false; } protected boolean refineAliasInternal(VarNode v1, VarNode v2, PointsToSetInternal intersection, HeuristicType heuristic) { this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return false; } if (numPasses > maxPasses) { return false; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); boolean success = false; try { AllocAndContextSet allocAndContexts = findContextsForAllocs( new VarAndContext(v1, EMPTY_CALLSTACK), intersection); boolean emptyIntersection = true; for (AllocAndContext allocAndContext : allocAndContexts) { CallingContextSet upContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(v2, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); if (!upContexts.isEmpty()) { emptyIntersection = false; break; } } success = emptyIntersection; } catch (TerminateEarlyException e) { success = false; } if (success) { G.v().out.println("took " + numPasses + " passes"); return true; } else { if (!fieldCheckHeuristic.runNewPass()) { return false; } } } } protected Set<SootMethod> refineCallSite(Integer callSite, ImmutableStack<Integer> origContext) { CallSiteAndContext callSiteAndContext = new CallSiteAndContext( callSite, origContext); if (queriedCallSites.contains(callSiteAndContext)) { // if (DEBUG_VIRT) { // final SootMethod invokedMethod = // csInfo.getInvokedMethod(callSite); // final VarNode receiver = // csInfo.getReceiverForVirtCallSite(callSite); // debugPrint("call of " + invokedMethod + " on " + receiver + " " // + origContext + " goes to " // + callSiteToResolvedTargets.get(callSiteAndContext)); // } return callSiteToResolvedTargets.get(callSiteAndContext); } if (callGraphStack.contains(callSiteAndContext)) { return Collections.<SootMethod> emptySet(); } else { callGraphStack.push(callSiteAndContext); } final VarNode receiver = csInfo.getReceiverForVirtCallSite(callSite); final Type receiverType = receiver.getType(); final SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); final NumberedString methodSig = invokedMethod .getNumberedSubSignature(); final Set<SootMethod> allTargets = csInfo.getCallSiteTargets(callSite); if (!refineCallGraph) { callGraphStack.pop(); return allTargets; } if (DEBUG_VIRT) { debugPrint("refining call to " + invokedMethod + " on " + receiver + " " + origContext); } final HashSet<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final class Helper { void prop(VarAndContext varAndContext) { if (marked.add(varAndContext)) { worklist.push(varAndContext); } } } ; final Helper h = new Helper(); h.prop(new VarAndContext(receiver, origContext)); while (!worklist.isEmpty()) { incrementNodesTraversed(); VarAndContext curVarAndContext = worklist.pop(); if (DEBUG_VIRT) { debugPrint("virt looking at " + curVarAndContext); } VarNode curVar = curVarAndContext.var; ImmutableStack<Integer> curContext = curVarAndContext.context; // Set<SootMethod> curVarTargets = getCallTargets(curVar.getP2Set(), // methodSig, receiverType, allTargets); // if (curVarTargets.size() <= 1) { // for (SootMethod method : curVarTargets) { // callSiteToResolvedTargets.put(callSiteAndContext, method); // } // continue; // } Node[] newNodes = pag.allocInvLookup(curVar); for (int i = 0; i < newNodes.length; i++) { AllocNode allocNode = (AllocNode) newNodes[i]; for (SootMethod method : getCallTargetsForType(allocNode .getType(), methodSig, receiverType, allTargets)) { callSiteToResolvedTargets.put(callSiteAndContext, method); } } Collection<AssignEdge> assigns = filterAssigns(curVar, curContext, true, true); for (AssignEdge assignEdge : assigns) { VarNode src = assignEdge.getSrc(); ImmutableStack<Integer> newContext = curContext; if (assignEdge.isParamEdge()) { if (!curContext.isEmpty()) { if (!callEdgeInSCC(assignEdge)) { assert assignEdge.getCallSite().equals( curContext.peek()); newContext = curContext.pop(); } else { newContext = popRecursiveCallSites(curContext); } } else { callSiteToResolvedTargets.putAll(callSiteAndContext, allTargets); // if (DEBUG) { // debugPrint("giving up on virt"); // } continue; } } else if (assignEdge.isReturnEdge()) { // if (DEBUG) // G.v().out.println("entering call site " // + assignEdge.getCallSite()); // if (!isRecursive(curContext, assignEdge)) { // newContext = curContext.push(assignEdge.getCallSite()); // } newContext = pushWithRecursionCheck(curContext, assignEdge); } else if (src instanceof GlobalVarNode) { newContext = EMPTY_CALLSTACK; } h.prop(new VarAndContext(src, newContext)); } // TODO respect heuristic Set<VarNode> matchSources = vMatches.vMatchInvLookup(curVar); final boolean oneMatch = matchSources.size() == 1; Node[] loads = pag.loadInvLookup(curVar); for (int i = 0; i < loads.length; i++) { FieldRefNode frNode = (FieldRefNode) loads[i]; final VarNode loadBase = frNode.getBase(); SparkField field = frNode.getField(); for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) { final VarNode storeBase = store.getO2(); final PointsToSetInternal storeBaseP2Set = storeBase .getP2Set(); final PointsToSetInternal loadBaseP2Set = loadBase .getP2Set(); final VarNode matchSrc = store.getO1(); if (matchSources.contains(matchSrc)) { // optimize for common case of constructor init boolean skipMatch = false; if (oneMatch) { PointsToSetInternal matchSrcPTo = matchSrc .getP2Set(); Set<SootMethod> matchSrcCallTargets = getCallTargets( matchSrcPTo, methodSig, receiverType, allTargets); if (matchSrcCallTargets.size() <= 1) { skipMatch = true; for (SootMethod method : matchSrcCallTargets) { callSiteToResolvedTargets.put( callSiteAndContext, method); } } } if (!skipMatch) { final PointsToSetInternal intersection = SootUtil .constructIntersection(storeBaseP2Set, loadBaseP2Set, pag); AllocAndContextSet allocContexts = null; boolean oldRefining = refiningCallSite; int oldNesting = nesting; try { refiningCallSite = true; allocContexts = findContextsForAllocs( new VarAndContext(loadBase, curContext), intersection); } catch (CallSiteException e) { callSiteToResolvedTargets.putAll( callSiteAndContext, allTargets); continue; } finally { refiningCallSite = oldRefining; nesting = oldNesting; } for (AllocAndContext allocAndContext : allocContexts) { CallingContextSet matchSrcContexts; if (fieldCheckHeuristic .validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { VarAndContext newVarAndContext = new VarAndContext( matchSrc, matchSrcContext); h.prop(newVarAndContext); } } } } } } } if (DEBUG_VIRT) { debugPrint("call of " + invokedMethod + " on " + receiver + " " + origContext + " goes to " + callSiteToResolvedTargets.get(callSiteAndContext)); } callGraphStack.pop(); queriedCallSites.add(callSiteAndContext); return callSiteToResolvedTargets.get(callSiteAndContext); } protected boolean refineP2Set(VarAndContext varAndContext, final PointsToSetInternal badLocs) { nesting++; if (DEBUG) { debugPrint("refining " + varAndContext); } final Set<VarAndContext> marked = new HashSet<VarAndContext>(); final Stack<VarAndContext> worklist = new Stack<VarAndContext>(); final Propagator<VarAndContext> p = new Propagator<VarAndContext>( marked, worklist); p.prop(varAndContext); IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() { boolean success = true; @Override public void handleAlloc(AllocNode allocNode, VarAndContext origVarAndContext) { if (doPointsTo && pointsTo != null) { pointsTo.add(new AllocAndContext(allocNode, origVarAndContext.context)); } else { if (badLocs.contains(allocNode)) { success = false; } } } @Override public void handleMatchSrc(VarNode matchSrc, PointsToSetInternal intersection, VarNode loadBase, VarNode storeBase, VarAndContext origVarAndContext, SparkField field, boolean refine) { AllocAndContextSet allocContexts = findContextsForAllocs( new VarAndContext(loadBase, origVarAndContext.context), intersection); for (AllocAndContext allocAndContext : allocContexts) { if (DEBUG) { debugPrint("alloc and context " + allocAndContext); } CallingContextSet matchSrcContexts; if (fieldCheckHeuristic.validFromBothEnds(field)) { matchSrcContexts = findUpContextsForVar( allocAndContext, new VarContextAndUp(storeBase, EMPTY_CALLSTACK, EMPTY_CALLSTACK)); } else { matchSrcContexts = findVarContextsFromAlloc( allocAndContext, storeBase); } for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) { if (DEBUG) debugPrint("match source context " + matchSrcContext); VarAndContext newVarAndContext = new VarAndContext( matchSrc, matchSrcContext); p.prop(newVarAndContext); } } } Object getResult() { return Boolean.valueOf(success); } @Override void handleAssignSrc(VarAndContext newVarAndContext, VarAndContext origVarAndContext, AssignEdge assignEdge) { p.prop(newVarAndContext); } @Override boolean shouldHandleSrc(VarNode src) { if (doPointsTo) { return true; } else { return src.getP2Set().hasNonEmptyIntersection(badLocs); } } boolean terminate() { return !success; } }; processIncomingEdges(edgeHandler, worklist); nesting--; return (Boolean) edgeHandler.getResult(); } /* * (non-Javadoc) * * @see AAA.summary.Refiner#refineP2Set(soot.jimple.spark.pag.VarNode, * soot.jimple.spark.sets.PointsToSetInternal) */ protected boolean refineP2Set(VarNode v, PointsToSetInternal badLocs, HeuristicType heuristic) { // G.v().out.println(badLocs); this.doPointsTo = false; this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag .getTypeManager(), getMaxPasses()); try { numPasses = 0; while (true) { numPasses++; if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) { return false; } if (numPasses > maxPasses) { return false; } if (DEBUG) { G.v().out.println("PASS " + numPasses); G.v().out.println(fieldCheckHeuristic); } clearState(); boolean success = false; try { success = refineP2Set( new VarAndContext(v, EMPTY_CALLSTACK), badLocs); } catch (TerminateEarlyException e) { success = false; } if (success) { return true; } else { if (!fieldCheckHeuristic.runNewPass()) { return false; } } } } finally { } } protected boolean weirdCall(Integer callSite) { SootMethod invokedMethod = csInfo.getInvokedMethod(callSite); return SootUtil.isThreadStartMethod(invokedMethod) || SootUtil.isNewInstanceMethod(invokedMethod); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Context c, Local l) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Context c, Local l, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(Local l, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(PointsToSet s, SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjects(SootField f) { throw new UnsupportedOperationException(); } /** * Currently not implemented. * * @throws UnsupportedOperationException * always */ public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) { throw new UnsupportedOperationException(); } /** * @return returns the (SPARK) pointer assignment graph */ public PAG getPAG() { return pag; } /** * @return <code>true</code> is caching is enabled */ public boolean usesCache() { return useCache; } /** * enables caching */ public void enableCache() { useCache = true; } /** * disables caching */ public void disableCache() { useCache = false; } /** * clears the cache */ public void clearCache() { reachingObjectsCache.clear(); } public boolean isRefineCallGraph() { return refineCallGraph; } public void setRefineCallGraph(boolean refineCallGraph) { this.refineCallGraph = refineCallGraph; } }
minor refactorings
src/soot/jimple/spark/ondemand/DemandCSPointsTo.java
minor refactorings
<ide><path>rc/soot/jimple/spark/ondemand/DemandCSPointsTo.java <ide> * Computes the possibly refined set of reaching objects for l. <ide> */ <ide> protected PointsToSet computeReachingObjects(Local l) { <del> PointsToSet result; <ide> VarNode v = pag.findLocalVarNode(l); <ide> if (v == null) { <add> //no reaching objects <ide> return EmptyPointsToSet.v(); <ide> } <add> PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v); <add> if(contextSensitiveResult == null ) { <add> //had to abort; return Spark's points-to set in a wrapper <add> return new WrappedPointsToSet(v.getP2Set()); <add> } else { <add> return contextSensitiveResult; <add> } <add> } <add> <add> /** <add> * Computes the refined set of reaching objects for l. <add> * Returns <code>null</code> if refinement failed. <add> */ <add> protected PointsToSet computeRefinedReachingObjects(VarNode v) { <ide> // must reset the refinement heuristic for each query <ide> this.fieldCheckHeuristic = HeuristicType.getHeuristic( <ide> HeuristicType.INCR, pag.getTypeManager(), getMaxPasses()); <ide> doPointsTo = true; <ide> numPasses = 0; <del> PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v); <del> if(contextSensitiveResult == null ) { <del> result = new WrappedPointsToSet(v.getP2Set()); <del> } else { <del> result = contextSensitiveResult; <del> } <del> return result; <del> } <del> <del> /** <del> * Computes the refined set of reaching objects for l. <del> * Returns <code>null</code> if refinement failed. <del> */ <del> protected PointsToSet computeRefinedReachingObjects(VarNode v) { <ide> PointsToSet contextSensitiveResult = null; <ide> while (true) { <ide> numPasses++;
Java
apache-2.0
0bd43a5427557c7f155a6ee00103369c76a49efb
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.NotNull; import java.util.EventListener; /** * Listener for {@link FileEditorManager} events. All methods are invoked in EDT. */ public interface FileEditorManagerListener extends EventListener{ Topic<FileEditorManagerListener> FILE_EDITOR_MANAGER = new Topic<>("file editor events", FileEditorManagerListener.class, Topic.BroadcastDirection.TO_PARENT); /** * This method is called synchronously (in the same EDT event), as the creation of FileEditor(s). * * @see #fileOpened(FileEditorManager, VirtualFile) */ default void fileOpenedSync(@NotNull FileEditorManager source, @NotNull VirtualFile file, @NotNull Pair<FileEditor[], FileEditorProvider[]> editors) { } /** * This method is after focus settles down (if requested) in newly created FileEditor. * {@link #fileOpenedSync(FileEditorManager, VirtualFile, Pair)} is always invoked before this method (in same or previous EDT event). * * @see #fileOpenedSync(FileEditorManager, VirtualFile, Pair) */ default void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void selectionChanged(@NotNull FileEditorManagerEvent event) { } interface Before extends EventListener { Topic<Before> FILE_EDITOR_MANAGER = new Topic<>("file editor before events", Before.class, Topic.BroadcastDirection.TO_PARENT); default void beforeFileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } /** * @deprecated use {@link Before} directly */ @Deprecated class Adapter implements Before { @Override public void beforeFileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } @Override public void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } } } }
platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManagerListener.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.NotNull; import java.util.EventListener; public interface FileEditorManagerListener extends EventListener{ Topic<FileEditorManagerListener> FILE_EDITOR_MANAGER = new Topic<>("file editor events", FileEditorManagerListener.class, Topic.BroadcastDirection.TO_PARENT); /** * This method is called synchronously (in the same EDT event), as the creation of FileEditor(s). * * @see #fileOpened(FileEditorManager, VirtualFile) */ default void fileOpenedSync(@NotNull FileEditorManager source, @NotNull VirtualFile file, @NotNull Pair<FileEditor[], FileEditorProvider[]> editors) { } /** * This method is after focus settles down (if requested) in newly created FileEditor. * {@link #fileOpenedSync(FileEditorManager, VirtualFile, Pair)} is always invoked before this method (in same or previous EDT event). * * @see #fileOpenedSync(FileEditorManager, VirtualFile, Pair) */ default void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void selectionChanged(@NotNull FileEditorManagerEvent event) { } interface Before extends EventListener { Topic<Before> FILE_EDITOR_MANAGER = new Topic<>("file editor before events", Before.class, Topic.BroadcastDirection.TO_PARENT); default void beforeFileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } default void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } /** * @deprecated use {@link Before} directly */ @Deprecated class Adapter implements Before { @Override public void beforeFileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } @Override public void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { } } } }
javadoc for FileEditorManagerListener
platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManagerListener.java
javadoc for FileEditorManagerListener
<ide><path>latform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManagerListener.java <ide> <ide> import java.util.EventListener; <ide> <add>/** <add> * Listener for {@link FileEditorManager} events. All methods are invoked in EDT. <add> */ <ide> public interface FileEditorManagerListener extends EventListener{ <ide> Topic<FileEditorManagerListener> FILE_EDITOR_MANAGER = <ide> new Topic<>("file editor events", FileEditorManagerListener.class, Topic.BroadcastDirection.TO_PARENT);
Java
mit
error: pathspec 'Coding_cyclotomic_cosets.java' did not match any file(s) known to git
2c54c4026d3d9c8c0701576c8ec593c521a4b0d1
1
thmavri/CyclotomicCosets
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package coding_cyclotomic_cosets; /** * * @author Themis Mavridis */ public class Coding_cyclotomic_cosets { /** * @param args the command line arguments */ //The following code calculates the cyclotomic cosets that are need for the calculation of idempotents modulo 1+x^n of some degree //e.g problem: Find the two idempotents modulo 1 +x^15 of degree 12 in which the constant term and the coefficient of x^5 are non-zero public static void main(String[] args) { int n=Integer.parseInt(args[0]); double coset=0; double power=0; int r=1; boolean rfound=false; while(!rfound){ if(Math.pow(2,r)%n==1){ rfound=true; } r++; } for(double i=0;i<n;i++){ System.out.print("\n\n---------------------- C ="+i+"-----------------"); for(double j=0;j<r-1;j++){ power=Math.pow((double)2,j); coset=(power*(i))%n; System.out.print("\nC"+i+"="+coset); } } } }
Coding_cyclotomic_cosets.java
Cyclotomic Cosets calculation The following code calculates the cyclotomic cosets that are need for the calculation of idempotents modulo 1+x^n of some degree
Coding_cyclotomic_cosets.java
Cyclotomic Cosets calculation
<ide><path>oding_cyclotomic_cosets.java <add>/* <add> * To change this template, choose Tools | Templates <add> * and open the template in the editor. <add> */ <add>package coding_cyclotomic_cosets; <add>/** <add> * <add> * @author Themis Mavridis <add> */ <add>public class Coding_cyclotomic_cosets { <add> <add> /** <add> * @param args the command line arguments <add> */ <add> //The following code calculates the cyclotomic cosets that are need for the calculation of idempotents modulo 1+x^n of some degree <add> //e.g problem: Find the two idempotents modulo 1 +x^15 of degree 12 in which the constant term and the coefficient of x^5 are non-zero <add> public static void main(String[] args) { <add> int n=Integer.parseInt(args[0]); <add> double coset=0; <add> double power=0; <add> int r=1; <add> boolean rfound=false; <add> while(!rfound){ <add> if(Math.pow(2,r)%n==1){ <add> rfound=true; <add> } <add> r++; <add> } <add> for(double i=0;i<n;i++){ <add> System.out.print("\n\n---------------------- C ="+i+"-----------------"); <add> for(double j=0;j<r-1;j++){ <add> power=Math.pow((double)2,j); <add> coset=(power*(i))%n; <add> System.out.print("\nC"+i+"="+coset); <add> } <add> } <add> <add> } <add>}
Java
bsd-3-clause
1eed103d31757025be4cbc7c587039a2aa9c8787
0
krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen
package com.krishagni.catissueplus.core.common.access; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.krishagni.catissueplus.core.administrative.domain.DistributionOrder; import com.krishagni.catissueplus.core.administrative.domain.Institute; import com.krishagni.catissueplus.core.administrative.domain.Site; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.domain.User; import com.krishagni.catissueplus.core.administrative.repository.UserDao; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.Visit; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.VisitErrorCode; import com.krishagni.catissueplus.core.common.Pair; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.Operation; import com.krishagni.catissueplus.core.common.events.Resource; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.rbac.common.errors.RbacErrorCode; import com.krishagni.rbac.domain.Subject; import com.krishagni.rbac.domain.SubjectAccess; import com.krishagni.rbac.domain.SubjectRole; import com.krishagni.rbac.repository.DaoFactory; import com.krishagni.rbac.service.RbacService; @Configurable public class AccessCtrlMgr { @Autowired private RbacService rbacService; @Autowired private DaoFactory daoFactory; @Autowired private UserDao userDao; private static AccessCtrlMgr instance; private AccessCtrlMgr() { } public static AccessCtrlMgr getInstance() { if (instance == null) { instance = new AccessCtrlMgr(); } return instance; } public void ensureUserIsAdmin() { User user = AuthUtil.getCurrentUser(); if (!user.isAdmin()) { throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // User object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateUserRights(User user) { ensureUserObjectRights(user, Operation.CREATE); } public void ensureUpdateUserRights(User user) { ensureUserObjectRights(user, Operation.UPDATE); } public void ensureDeleteUserRights(User user) { ensureUserObjectRights(user, Operation.DELETE); } private void ensureUserObjectRights(User user, Operation op) { if (AuthUtil.isAdmin()) { return; } if (user.isAdmin() && op != Operation.READ) { throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED); } Set<Site> sites = getSites(Resource.USER, op); for (Site site : sites) { if (site.getInstitute().equals(user.getInstitute())) { return; } } throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } ////////////////////////////////////////////////////////////////////////////////////// // // // Distribution Protocol object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureReadDpRights() { if (AuthUtil.isAdmin()) { return; } User user = AuthUtil.getCurrentUser(); Operation[] ops = {Operation.CREATE, Operation.UPDATE}; if (!canUserPerformOp(user.getId(), Resource.ORDER, ops)) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Collection Protocol object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadableCpIds() { return getEligibleCpIds(Resource.CP.getName(), Operation.READ.getName(), null); } public Set<Long> getRegisterEnabledCpIds(List<String> siteNames) { return getEligibleCpIds(Resource.PARTICIPANT.getName(), Operation.CREATE.getName(), siteNames); } public void ensureCreateCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.CREATE); } public void ensureReadCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.READ); } public void ensureUpdateCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.UPDATE); } public void ensureDeleteCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.DELETE); } private void ensureCpObjectRights(CollectionProtocol cp, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.CP.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); CollectionProtocol accessCp = access.getCollectionProtocol(); if (accessSite != null && accessCp != null && accessCp.equals(cp)) { // // Specific CP // allowed = true; } else if (accessSite != null && accessCp == null && cp.getRepositories().contains(accessSite)) { // // TODO: // Current implementation is at least one site is CP repository. We do not check whether permission is // for all CP repositories. // // All CPs of a site // allowed = true; } else if (accessSite == null && accessCp == null) { // // All CPs of all sites of user institute // Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) { allowed = true; } } else if (accessSite == null && accessCp != null && accessCp.equals(cp)) { // // Specific CP of all sites // Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Participant object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public static class ParticipantReadAccess { public boolean admin; public Set<Long> siteIds; public boolean phiAccess; } public ParticipantReadAccess getParticipantReadAccess(Long cpId) { ParticipantReadAccess result = new ParticipantReadAccess(); result.phiAccess = true; if (AuthUtil.isAdmin()) { result.admin = true; return result; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.PARTICIPANT.getName(); String[] ops = {Operation.READ.getName()}; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); if (accessList.isEmpty()) { resource = Resource.PARTICIPANT_DEID.getName(); accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); result.phiAccess = false; } Set<Long> siteIds = new HashSet<Long>(); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null) { siteIds.add(accessSite.getId()); } else if (accessSite == null) { Set<Site> sites = getUserInstituteSites(userId); for (Site site : sites) { siteIds.add(site.getId()); } } } result.siteIds = siteIds; return result; } public boolean ensureCreateCprRights(Long cprId) { return ensureCprObjectRights(cprId, Operation.CREATE); } public boolean ensureCreateCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.CREATE); } public void ensureReadCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.READ); } public boolean ensureReadCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.READ); } public void ensureUpdateCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.UPDATE); } public boolean ensureUpdateCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.UPDATE); } public void ensureDeleteCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.DELETE); } public boolean ensureDeleteCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.DELETE); } private boolean ensureCprObjectRights(Long cprId, Operation op) { CollectionProtocolRegistration cpr = daoFactory.getCprDao().getById(cprId); if (cpr == null) { throw OpenSpecimenException.userError(CprErrorCode.NOT_FOUND); } return ensureCprObjectRights(cpr, op); } private boolean ensureCprObjectRights(CollectionProtocolRegistration cpr, Operation op) { if (AuthUtil.isAdmin()) { return true; } Long userId = AuthUtil.getCurrentUser().getId(); boolean phiAccess = true; String resource = Resource.PARTICIPANT.getName(); String[] ops = {op.getName()}; boolean allowed = false; Long cpId = cpr.getCollectionProtocol().getId(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); if (accessList.isEmpty() && op == Operation.READ) { phiAccess = false; resource = Resource.PARTICIPANT_DEID.getName(); accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); } if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Set<Site> mrnSites = cpr.getParticipant().getMrnSites(); if (mrnSites.isEmpty()) { return phiAccess; } for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, mrnSites)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } return phiAccess; } ////////////////////////////////////////////////////////////////////////////////////// // // // Visit and Specimen object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateOrUpdateVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.UPDATE); } public void ensureCreateOrUpdateVisitRights(Visit visit) { ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.UPDATE); } public void ensureReadVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.READ); } public void ensureReadVisitRights(Visit visit) { ensureReadVisitRights(visit.getRegistration()); } public void ensureReadVisitRights(CollectionProtocolRegistration cpr) { ensureVisitAndSpecimenObjectRights(cpr, Operation.READ); } public void ensureDeleteVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.DELETE); } public void ensureDeleteVisitRights(Visit visit) { ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.DELETE); } public void ensureCreateOrUpdateSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.UPDATE); } public void ensureCreateOrUpdateSpecimenRights(Specimen specimen) { ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.UPDATE); } public void ensureReadSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.READ); } public void ensureReadSpecimenRights(Specimen specimen) { ensureReadSpecimenRights(specimen.getRegistration()); } public void ensureReadSpecimenRights(CollectionProtocolRegistration cpr) { ensureVisitAndSpecimenObjectRights(cpr, Operation.READ); } public void ensureDeleteSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.DELETE); } public void ensureDeleteSpecimenRights(Specimen specimen) { ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.DELETE); } public List<Pair<Long, Long>> getReadAccessSpecimenSiteCps() { if (AuthUtil.isAdmin()) { return null; } String[] ops = {Operation.READ.getName()}; Set<Pair<Long, Long>> siteCpPairs = getVisitAndSpecimenSiteCps(ops); siteCpPairs.addAll(getDistributionOrderSiteCps(ops)); Set<Long> sitesOfAllCps = new HashSet<Long>(); List<Pair<Long, Long>> result = new ArrayList<Pair<Long, Long>>(); for (Pair<Long, Long> siteCp : siteCpPairs) { if (siteCp.second() == null) { sitesOfAllCps.add(siteCp.first()); result.add(siteCp); } } for (Pair<Long, Long> siteCp : siteCpPairs) { if (sitesOfAllCps.contains(siteCp.first())) { continue; } result.add(siteCp); } return result; } private void ensureVisitObjectRights(Long visitId, Operation op) { Visit visit = daoFactory.getVisitDao().getById(visitId); if (visit == null) { throw OpenSpecimenException.userError(VisitErrorCode.NOT_FOUND); } ensureVisitAndSpecimenObjectRights(visit.getRegistration(), op); } private void ensureSpecimenObjectRights(Long specimenId, Operation op) { Specimen specimen = daoFactory.getSpecimenDao().getById(specimenId); if (specimen == null) { throw OpenSpecimenException.userError(SpecimenErrorCode.NOT_FOUND, specimenId); } ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), op); } private void ensureVisitAndSpecimenObjectRights(CollectionProtocolRegistration cpr, Operation op) { if (AuthUtil.isAdmin()) { return; } String[] ops = null; if (op == Operation.CREATE || op == Operation.UPDATE) { ops = new String[]{Operation.CREATE.getName(), Operation.UPDATE.getName()}; } else { ops = new String[]{op.getName()}; } ensureSprOrVisitAndSpecimenObjectRights(cpr, Resource.VISIT_N_SPECIMEN, ops); } private Set<Pair<Long, Long>> getVisitAndSpecimenSiteCps(String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.VISIT_N_SPECIMEN.getName(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>(); for (SubjectAccess access : accessList) { Set<Site> sites = null; if (access.getSite() != null) { sites = Collections.singleton(access.getSite()); } else { sites = getUserInstituteSites(userId); } Long cpId = null; if (access.getCollectionProtocol() != null) { cpId = access.getCollectionProtocol().getId(); } for (Site site : sites) { siteCpPairs.add(Pair.make(site.getId(), cpId)); } } return siteCpPairs; } ////////////////////////////////////////////////////////////////////////////////////// // // // Storage container object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadAccessContainerSites() { if (AuthUtil.isAdmin()) { return null; } Set<Site> sites = getSites(Resource.STORAGE_CONTAINER, Operation.READ); Set<Long> result = new HashSet<Long>(); for (Site site : sites) { result.add(site.getId()); } return result; } public void ensureCreateContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.CREATE); } public void ensureCreateContainerRights(Site containerSite) { ensureStorageContainerObjectRights(containerSite, Operation.CREATE); } public void ensureReadContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.READ); } public void ensureUpdateContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.UPDATE); } public void ensureDeleteContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.DELETE); } private void ensureStorageContainerObjectRights(StorageContainer container, Operation op) { if (AuthUtil.isAdmin()) { return; } ensureStorageContainerObjectRights(container.getSite(), op); } private void ensureStorageContainerObjectRights(Site containerSite, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.STORAGE_CONTAINER.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && accessSite.equals(containerSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (instituteSites.contains(containerSite)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Distribution order access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadAccessDistributionOrderInstitutes() { if (AuthUtil.isAdmin()) { return null; } Set<Site> sites = getSites(Resource.ORDER, Operation.READ); Set<Long> result = new HashSet<Long>(); for (Site site : sites) { result.add(site.getInstitute().getId()); } return result; } public void ensureCreateDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.CREATE); } public void ensureReadDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.READ); } public void ensureUpdateDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.UPDATE); } public void ensureDeleteDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.DELETE); } private void ensureDistributionOrderObjectRights(DistributionOrder order, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.ORDER.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Institute orderInstitute = order.getInstitute(); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && accessSite.getInstitute().equals(orderInstitute)) { // Specific site institute allowed = true; } else if (accessSite == null) { // user institute Institute userInstitute = getUserInstitute(userId); if (userInstitute.equals(orderInstitute)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } private Set<Pair<Long, Long>> getDistributionOrderSiteCps(String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.ORDER.getName(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>(); for (SubjectAccess access : accessList) { Set<Site> sites = null; if (access.getSite() != null) { sites = access.getSite().getInstitute().getSites(); } else { sites = getUserInstituteSites(userId); } for (Site site : sites) { siteCpPairs.add(Pair.make(site.getId(), (Long) null)); } } return siteCpPairs; } public Set<Site> getRoleAssignedSites() { User user = AuthUtil.getCurrentUser(); Subject subject = daoFactory.getSubjectDao().getById(user.getId()); Set<Site> results = new HashSet<Site>(); boolean allSites = false; for (SubjectRole role : subject.getRoles()) { if (role.getSite() == null) { allSites = true; break; } results.add(role.getSite()); } if (allSites) { results.clear(); results.addAll(getUserInstituteSites(user.getId())); } return results; } public Set<Site> getSites(Resource resource, Operation operation) { User user = AuthUtil.getCurrentUser(); String[] ops = {operation.getName()}; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(user.getId(), resource.getName(), ops); Set<Site> results = new HashSet<Site>(); boolean allSites = false; for (SubjectAccess access : accessList) { if (access.getSite() == null) { allSites = true; break; } results.add(access.getSite()); } if (allSites) { results.clear(); results.addAll(getUserInstituteSites(user.getId())); } return results; } public Set<Long> getEligibleCpIds(String resource, String op, List<String> siteNames) { if (AuthUtil.isAdmin()) { return null; } Long userId = AuthUtil.getCurrentUser().getId(); String[] ops = {op}; List<SubjectAccess> accessList = null; if (CollectionUtils.isEmpty(siteNames)) { accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); } else { accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops, siteNames.toArray(new String[0])); } Set<Long> cpIds = new HashSet<Long>(); Set<Long> cpOfSites = new HashSet<Long>(); for (SubjectAccess access : accessList) { if (access.getSite() != null && access.getCollectionProtocol() != null) { cpIds.add(access.getCollectionProtocol().getId()); } else if (access.getSite() != null) { cpOfSites.add(access.getSite().getId()); } else if (access.getSite() == null && access.getCollectionProtocol() != null) { cpIds.add(access.getCollectionProtocol().getId()); } else { Collection<Site> sites = getUserInstituteSites(userId); for (Site site : sites) { if (CollectionUtils.isEmpty(siteNames) || siteNames.contains(site.getName())) { cpOfSites.add(site.getId()); } } } } if (!cpOfSites.isEmpty()) { cpIds.addAll(daoFactory.getCollectionProtocolDao().getCpIdsBySiteIds(cpOfSites)); } return cpIds; } private Set<Site> getUserInstituteSites(Long userId) { return getUserInstitute(userId).getSites(); } private Institute getUserInstitute(Long userId) { User user = userDao.getById(userId); return user.getInstitute(); } private boolean canUserPerformOp(Long userId, Resource resource, Operation[] operations) { List<String> ops = new ArrayList<String>(); for (Operation operation : operations) { ops.add(operation.getName()); } return daoFactory.getSubjectDao().canUserPerformOps( userId, resource.getName(), ops.toArray(new String[0])); } ////////////////////////////////////////////////////////////////////////////////////// // // // Surgical pathology report access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateOrUpdateSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.UPDATE); } public void ensureDeleteSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.DELETE); } public void ensureReadSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.READ); } public void ensureLockSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.LOCK); } public void ensureUnlockSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.UNLOCK); } private void ensureSprObjectRights(Visit visit, Operation op) { if (AuthUtil.isAdmin()) { return; } if (op == Operation.LOCK || op == Operation.UNLOCK) { ensureCreateOrUpdateVisitRights(visit); } else { ensureVisitObjectRights(visit.getId(), op); } CollectionProtocolRegistration cpr = visit.getRegistration(); String[] ops = {op.getName()}; ensureSprOrVisitAndSpecimenObjectRights(cpr, Resource.SURGICAL_PATHOLOGY_REPORT, ops); } private void ensureSprOrVisitAndSpecimenObjectRights(CollectionProtocolRegistration cpr, Resource resource, String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); Long cpId = cpr.getCollectionProtocol().getId(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource.getName(), ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Set<Site> mrnSites = cpr.getParticipant().getMrnSites(); if (mrnSites.isEmpty()) { return; } boolean allowed = false; for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, mrnSites)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Scheduled Job object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureReadScheduledJobRights() { Operation[] ops = {Operation.READ}; ensureScheduledJobRights(ops); } public void ensureRunJobRights() { Operation[] ops = {Operation.READ}; ensureScheduledJobRights(ops); } public void ensureCreateScheduledJobRights() { Operation[] ops = {Operation.CREATE}; ensureScheduledJobRights(ops); } public void ensureUpdateScheduledJobRights() { Operation[] ops = {Operation.UPDATE}; ensureScheduledJobRights(ops); } public void ensureDeleteScheduledJobRights() { Operation[] ops = {Operation.DELETE}; ensureScheduledJobRights(ops); } public void ensureScheduledJobRights(Operation[] ops) { if (AuthUtil.isAdmin()) { return; } User user = AuthUtil.getCurrentUser(); if (!canUserPerformOp(user.getId(), Resource.SCHEDULED_JOB, ops)) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } }
WEB-INF/src/com/krishagni/catissueplus/core/common/access/AccessCtrlMgr.java
package com.krishagni.catissueplus.core.common.access; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.krishagni.catissueplus.core.administrative.domain.DistributionOrder; import com.krishagni.catissueplus.core.administrative.domain.Institute; import com.krishagni.catissueplus.core.administrative.domain.Site; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.domain.User; import com.krishagni.catissueplus.core.administrative.repository.UserDao; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.Visit; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.VisitErrorCode; import com.krishagni.catissueplus.core.common.Pair; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.Operation; import com.krishagni.catissueplus.core.common.events.Resource; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.rbac.common.errors.RbacErrorCode; import com.krishagni.rbac.domain.Subject; import com.krishagni.rbac.domain.SubjectAccess; import com.krishagni.rbac.domain.SubjectRole; import com.krishagni.rbac.repository.DaoFactory; import com.krishagni.rbac.service.RbacService; @Configurable public class AccessCtrlMgr { @Autowired private RbacService rbacService; @Autowired private DaoFactory daoFactory; @Autowired private UserDao userDao; private static AccessCtrlMgr instance; private AccessCtrlMgr() { } public static AccessCtrlMgr getInstance() { if (instance == null) { instance = new AccessCtrlMgr(); } return instance; } public void ensureUserIsAdmin() { User user = AuthUtil.getCurrentUser(); if (!user.isAdmin()) { throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // User object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateUserRights(User user) { ensureUserObjectRights(user, Operation.CREATE); } public void ensureUpdateUserRights(User user) { ensureUserObjectRights(user, Operation.UPDATE); } public void ensureDeleteUserRights(User user) { ensureUserObjectRights(user, Operation.DELETE); } private void ensureUserObjectRights(User user, Operation op) { if (AuthUtil.isAdmin()) { return; } if (user.isAdmin() && op != Operation.READ) { throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED); } Set<Site> sites = getSites(Resource.USER, op); for (Site site : sites) { if (site.getInstitute().equals(user.getInstitute())) { return; } } throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } ////////////////////////////////////////////////////////////////////////////////////// // // // Distribution Protocol object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureReadDpRights() { if (AuthUtil.isAdmin()) { return; } User user = AuthUtil.getCurrentUser(); Operation[] ops = {Operation.CREATE, Operation.UPDATE}; if (!canUserPerformOp(user.getId(), Resource.ORDER, ops)) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Collection Protocol object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadableCpIds() { return getEligibleCpIds(Resource.CP.getName(), Operation.READ.getName(), null); } public Set<Long> getRegisterEnabledCpIds(List<String> siteNames) { return getEligibleCpIds(Resource.PARTICIPANT.getName(), Operation.CREATE.getName(), siteNames); } public void ensureCreateCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.CREATE); } public void ensureReadCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.READ); } public void ensureUpdateCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.UPDATE); } public void ensureDeleteCpRights(CollectionProtocol cp) { ensureCpObjectRights(cp, Operation.DELETE); } private void ensureCpObjectRights(CollectionProtocol cp, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.CP.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); CollectionProtocol accessCp = access.getCollectionProtocol(); if (accessSite != null && accessCp != null && accessCp.equals(cp)) { // // Specific CP // allowed = true; } else if (accessSite != null && accessCp == null && cp.getRepositories().contains(accessSite)) { // // TODO: // Current implementation is at least one site is CP repository. We do not check whether permission is // for all CP repositories. // // All CPs of a site // allowed = true; } else if (accessSite == null && accessCp == null) { // // All CPs of all sites of user institute // Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Participant object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public static class ParticipantReadAccess { public boolean admin; public Set<Long> siteIds; public boolean phiAccess; } public ParticipantReadAccess getParticipantReadAccess(Long cpId) { ParticipantReadAccess result = new ParticipantReadAccess(); result.phiAccess = true; if (AuthUtil.isAdmin()) { result.admin = true; return result; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.PARTICIPANT.getName(); String[] ops = {Operation.READ.getName()}; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); if (accessList.isEmpty()) { resource = Resource.PARTICIPANT_DEID.getName(); accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); result.phiAccess = false; } Set<Long> siteIds = new HashSet<Long>(); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null) { siteIds.add(accessSite.getId()); } else if (accessSite == null) { Set<Site> sites = getUserInstituteSites(userId); for (Site site : sites) { siteIds.add(site.getId()); } } } result.siteIds = siteIds; return result; } public boolean ensureCreateCprRights(Long cprId) { return ensureCprObjectRights(cprId, Operation.CREATE); } public boolean ensureCreateCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.CREATE); } public void ensureReadCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.READ); } public boolean ensureReadCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.READ); } public void ensureUpdateCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.UPDATE); } public boolean ensureUpdateCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.UPDATE); } public void ensureDeleteCprRights(Long cprId) { ensureCprObjectRights(cprId, Operation.DELETE); } public boolean ensureDeleteCprRights(CollectionProtocolRegistration cpr) { return ensureCprObjectRights(cpr, Operation.DELETE); } private boolean ensureCprObjectRights(Long cprId, Operation op) { CollectionProtocolRegistration cpr = daoFactory.getCprDao().getById(cprId); if (cpr == null) { throw OpenSpecimenException.userError(CprErrorCode.NOT_FOUND); } return ensureCprObjectRights(cpr, op); } private boolean ensureCprObjectRights(CollectionProtocolRegistration cpr, Operation op) { if (AuthUtil.isAdmin()) { return true; } Long userId = AuthUtil.getCurrentUser().getId(); boolean phiAccess = true; String resource = Resource.PARTICIPANT.getName(); String[] ops = {op.getName()}; boolean allowed = false; Long cpId = cpr.getCollectionProtocol().getId(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); if (accessList.isEmpty() && op == Operation.READ) { phiAccess = false; resource = Resource.PARTICIPANT_DEID.getName(); accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops); } if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Set<Site> mrnSites = cpr.getParticipant().getMrnSites(); if (mrnSites.isEmpty()) { return phiAccess; } for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, mrnSites)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } return phiAccess; } ////////////////////////////////////////////////////////////////////////////////////// // // // Visit and Specimen object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateOrUpdateVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.UPDATE); } public void ensureCreateOrUpdateVisitRights(Visit visit) { ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.UPDATE); } public void ensureReadVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.READ); } public void ensureReadVisitRights(Visit visit) { ensureReadVisitRights(visit.getRegistration()); } public void ensureReadVisitRights(CollectionProtocolRegistration cpr) { ensureVisitAndSpecimenObjectRights(cpr, Operation.READ); } public void ensureDeleteVisitRights(Long visitId) { ensureVisitObjectRights(visitId, Operation.DELETE); } public void ensureDeleteVisitRights(Visit visit) { ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.DELETE); } public void ensureCreateOrUpdateSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.UPDATE); } public void ensureCreateOrUpdateSpecimenRights(Specimen specimen) { ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.UPDATE); } public void ensureReadSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.READ); } public void ensureReadSpecimenRights(Specimen specimen) { ensureReadSpecimenRights(specimen.getRegistration()); } public void ensureReadSpecimenRights(CollectionProtocolRegistration cpr) { ensureVisitAndSpecimenObjectRights(cpr, Operation.READ); } public void ensureDeleteSpecimenRights(Long specimenId) { ensureSpecimenObjectRights(specimenId, Operation.DELETE); } public void ensureDeleteSpecimenRights(Specimen specimen) { ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.DELETE); } public List<Pair<Long, Long>> getReadAccessSpecimenSiteCps() { if (AuthUtil.isAdmin()) { return null; } String[] ops = {Operation.READ.getName()}; Set<Pair<Long, Long>> siteCpPairs = getVisitAndSpecimenSiteCps(ops); siteCpPairs.addAll(getDistributionOrderSiteCps(ops)); Set<Long> sitesOfAllCps = new HashSet<Long>(); List<Pair<Long, Long>> result = new ArrayList<Pair<Long, Long>>(); for (Pair<Long, Long> siteCp : siteCpPairs) { if (siteCp.second() == null) { sitesOfAllCps.add(siteCp.first()); result.add(siteCp); } } for (Pair<Long, Long> siteCp : siteCpPairs) { if (sitesOfAllCps.contains(siteCp.first())) { continue; } result.add(siteCp); } return result; } private void ensureVisitObjectRights(Long visitId, Operation op) { Visit visit = daoFactory.getVisitDao().getById(visitId); if (visit == null) { throw OpenSpecimenException.userError(VisitErrorCode.NOT_FOUND); } ensureVisitAndSpecimenObjectRights(visit.getRegistration(), op); } private void ensureSpecimenObjectRights(Long specimenId, Operation op) { Specimen specimen = daoFactory.getSpecimenDao().getById(specimenId); if (specimen == null) { throw OpenSpecimenException.userError(SpecimenErrorCode.NOT_FOUND, specimenId); } ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), op); } private void ensureVisitAndSpecimenObjectRights(CollectionProtocolRegistration cpr, Operation op) { if (AuthUtil.isAdmin()) { return; } String[] ops = null; if (op == Operation.CREATE || op == Operation.UPDATE) { ops = new String[]{Operation.CREATE.getName(), Operation.UPDATE.getName()}; } else { ops = new String[]{op.getName()}; } ensureSprOrVisitAndSpecimenObjectRights(cpr, Resource.VISIT_N_SPECIMEN, ops); } private Set<Pair<Long, Long>> getVisitAndSpecimenSiteCps(String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.VISIT_N_SPECIMEN.getName(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>(); for (SubjectAccess access : accessList) { Set<Site> sites = null; if (access.getSite() != null) { sites = Collections.singleton(access.getSite()); } else { sites = getUserInstituteSites(userId); } Long cpId = null; if (access.getCollectionProtocol() != null) { cpId = access.getCollectionProtocol().getId(); } for (Site site : sites) { siteCpPairs.add(Pair.make(site.getId(), cpId)); } } return siteCpPairs; } ////////////////////////////////////////////////////////////////////////////////////// // // // Storage container object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadAccessContainerSites() { if (AuthUtil.isAdmin()) { return null; } Set<Site> sites = getSites(Resource.STORAGE_CONTAINER, Operation.READ); Set<Long> result = new HashSet<Long>(); for (Site site : sites) { result.add(site.getId()); } return result; } public void ensureCreateContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.CREATE); } public void ensureCreateContainerRights(Site containerSite) { ensureStorageContainerObjectRights(containerSite, Operation.CREATE); } public void ensureReadContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.READ); } public void ensureUpdateContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.UPDATE); } public void ensureDeleteContainerRights(StorageContainer container) { ensureStorageContainerObjectRights(container, Operation.DELETE); } private void ensureStorageContainerObjectRights(StorageContainer container, Operation op) { if (AuthUtil.isAdmin()) { return; } ensureStorageContainerObjectRights(container.getSite(), op); } private void ensureStorageContainerObjectRights(Site containerSite, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.STORAGE_CONTAINER.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && accessSite.equals(containerSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (instituteSites.contains(containerSite)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Distribution order access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public Set<Long> getReadAccessDistributionOrderInstitutes() { if (AuthUtil.isAdmin()) { return null; } Set<Site> sites = getSites(Resource.ORDER, Operation.READ); Set<Long> result = new HashSet<Long>(); for (Site site : sites) { result.add(site.getInstitute().getId()); } return result; } public void ensureCreateDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.CREATE); } public void ensureReadDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.READ); } public void ensureUpdateDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.UPDATE); } public void ensureDeleteDistributionOrderRights(DistributionOrder order) { ensureDistributionOrderObjectRights(order, Operation.DELETE); } private void ensureDistributionOrderObjectRights(DistributionOrder order, Operation op) { if (AuthUtil.isAdmin()) { return; } Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.ORDER.getName(); String[] ops = {op.getName()}; boolean allowed = false; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Institute orderInstitute = order.getInstitute(); for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && accessSite.getInstitute().equals(orderInstitute)) { // Specific site institute allowed = true; } else if (accessSite == null) { // user institute Institute userInstitute = getUserInstitute(userId); if (userInstitute.equals(orderInstitute)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } private Set<Pair<Long, Long>> getDistributionOrderSiteCps(String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); String resource = Resource.ORDER.getName(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>(); for (SubjectAccess access : accessList) { Set<Site> sites = null; if (access.getSite() != null) { sites = access.getSite().getInstitute().getSites(); } else { sites = getUserInstituteSites(userId); } for (Site site : sites) { siteCpPairs.add(Pair.make(site.getId(), (Long) null)); } } return siteCpPairs; } public Set<Site> getRoleAssignedSites() { User user = AuthUtil.getCurrentUser(); Subject subject = daoFactory.getSubjectDao().getById(user.getId()); Set<Site> results = new HashSet<Site>(); boolean allSites = false; for (SubjectRole role : subject.getRoles()) { if (role.getSite() == null) { allSites = true; break; } results.add(role.getSite()); } if (allSites) { results.clear(); results.addAll(getUserInstituteSites(user.getId())); } return results; } public Set<Site> getSites(Resource resource, Operation operation) { User user = AuthUtil.getCurrentUser(); String[] ops = {operation.getName()}; List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(user.getId(), resource.getName(), ops); Set<Site> results = new HashSet<Site>(); boolean allSites = false; for (SubjectAccess access : accessList) { if (access.getSite() == null) { allSites = true; break; } results.add(access.getSite()); } if (allSites) { results.clear(); results.addAll(getUserInstituteSites(user.getId())); } return results; } public Set<Long> getEligibleCpIds(String resource, String op, List<String> siteNames) { if (AuthUtil.isAdmin()) { return null; } Long userId = AuthUtil.getCurrentUser().getId(); String[] ops = {op}; List<SubjectAccess> accessList = null; if (CollectionUtils.isEmpty(siteNames)) { accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops); } else { accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops, siteNames.toArray(new String[0])); } Set<Long> cpIds = new HashSet<Long>(); Set<Long> cpOfSites = new HashSet<Long>(); for (SubjectAccess access : accessList) { if (access.getSite() != null && access.getCollectionProtocol() != null) { cpIds.add(access.getCollectionProtocol().getId()); } else if (access.getSite() != null) { cpOfSites.add(access.getSite().getId()); } else { Collection<Site> sites = getUserInstituteSites(userId); for (Site site : sites) { if (CollectionUtils.isEmpty(siteNames) || siteNames.contains(site.getName())) { cpOfSites.add(site.getId()); } } } } if (!cpOfSites.isEmpty()) { cpIds.addAll(daoFactory.getCollectionProtocolDao().getCpIdsBySiteIds(cpOfSites)); } return cpIds; } private Set<Site> getUserInstituteSites(Long userId) { return getUserInstitute(userId).getSites(); } private Institute getUserInstitute(Long userId) { User user = userDao.getById(userId); return user.getInstitute(); } private boolean canUserPerformOp(Long userId, Resource resource, Operation[] operations) { List<String> ops = new ArrayList<String>(); for (Operation operation : operations) { ops.add(operation.getName()); } return daoFactory.getSubjectDao().canUserPerformOps( userId, resource.getName(), ops.toArray(new String[0])); } ////////////////////////////////////////////////////////////////////////////////////// // // // Surgical pathology report access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureCreateOrUpdateSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.UPDATE); } public void ensureDeleteSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.DELETE); } public void ensureReadSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.READ); } public void ensureLockSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.LOCK); } public void ensureUnlockSprRights(Visit visit) { ensureSprObjectRights(visit, Operation.UNLOCK); } private void ensureSprObjectRights(Visit visit, Operation op) { if (AuthUtil.isAdmin()) { return; } if (op == Operation.LOCK || op == Operation.UNLOCK) { ensureCreateOrUpdateVisitRights(visit); } else { ensureVisitObjectRights(visit.getId(), op); } CollectionProtocolRegistration cpr = visit.getRegistration(); String[] ops = {op.getName()}; ensureSprOrVisitAndSpecimenObjectRights(cpr, Resource.SURGICAL_PATHOLOGY_REPORT, ops); } private void ensureSprOrVisitAndSpecimenObjectRights(CollectionProtocolRegistration cpr, Resource resource, String[] ops) { Long userId = AuthUtil.getCurrentUser().getId(); Long cpId = cpr.getCollectionProtocol().getId(); List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource.getName(), ops); if (accessList.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } Set<Site> mrnSites = cpr.getParticipant().getMrnSites(); if (mrnSites.isEmpty()) { return; } boolean allowed = false; for (SubjectAccess access : accessList) { Site accessSite = access.getSite(); if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site allowed = true; } else if (accessSite == null) { // All user institute sites Set<Site> instituteSites = getUserInstituteSites(userId); if (CollectionUtils.containsAny(instituteSites, mrnSites)) { allowed = true; } } if (allowed) { break; } } if (!allowed) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } ////////////////////////////////////////////////////////////////////////////////////// // // // Scheduled Job object access control helper methods // // // ////////////////////////////////////////////////////////////////////////////////////// public void ensureReadScheduledJobRights() { Operation[] ops = {Operation.READ}; ensureScheduledJobRights(ops); } public void ensureRunJobRights() { Operation[] ops = {Operation.READ}; ensureScheduledJobRights(ops); } public void ensureCreateScheduledJobRights() { Operation[] ops = {Operation.CREATE}; ensureScheduledJobRights(ops); } public void ensureUpdateScheduledJobRights() { Operation[] ops = {Operation.UPDATE}; ensureScheduledJobRights(ops); } public void ensureDeleteScheduledJobRights() { Operation[] ops = {Operation.DELETE}; ensureScheduledJobRights(ops); } public void ensureScheduledJobRights(Operation[] ops) { if (AuthUtil.isAdmin()) { return; } User user = AuthUtil.getCurrentUser(); if (!canUserPerformOp(user.getId(), Resource.SCHEDULED_JOB, ops)) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } } }
OPSMN - 2271 Cause: Get cps and access specific cp, case to allow access cp which is for all current and future sites not handled. Fix: Allow access collection protocol if its assigned to all current and future cps
WEB-INF/src/com/krishagni/catissueplus/core/common/access/AccessCtrlMgr.java
OPSMN - 2271
<ide><path>EB-INF/src/com/krishagni/catissueplus/core/common/access/AccessCtrlMgr.java <ide> if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) { <ide> allowed = true; <ide> } <add> } else if (accessSite == null && accessCp != null && accessCp.equals(cp)) { <add> // <add> // Specific CP of all sites <add> // <add> Set<Site> instituteSites = getUserInstituteSites(userId); <add> if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) { <add> allowed = true; <add> } <ide> } <ide> <ide> if (allowed) { <ide> cpIds.add(access.getCollectionProtocol().getId()); <ide> } else if (access.getSite() != null) { <ide> cpOfSites.add(access.getSite().getId()); <del> } else { <add> } else if (access.getSite() == null && access.getCollectionProtocol() != null) { <add> cpIds.add(access.getCollectionProtocol().getId()); <add> } else { <ide> Collection<Site> sites = getUserInstituteSites(userId); <ide> for (Site site : sites) { <ide> if (CollectionUtils.isEmpty(siteNames) || siteNames.contains(site.getName())) {
Java
bsd-2-clause
a5ba4b8051c16dccc50fd39a987307958d9c2b5f
0
sebastianscatularo/javadns,sebastianscatularo/javadns
// Copyright (c) 1999-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Options - describes Extended DNS (EDNS) properties of a Message. * No specific options are defined other than those specified in the * header. An OPT should be generated by Resolver. * * EDNS is a method to extend the DNS protocol while providing backwards * compatibility and not significantly changing the protocol. This * implementation of EDNS is mostly complete at level 0. * * @see Message * @see Resolver * * @author Brian Wellington */ public class OPTRecord extends Record { public static class Option { public final int code; public final byte [] data; /** * Creates an option with the given option code and data. */ public Option(int code, byte [] data) { this.code = checkU8("option code", code); this.data = data; } public String toString() { return "{" + code + " <" + base16.toString(data) + ">}"; } } private List options; OPTRecord() {} Record getObject() { return new OPTRecord(); } /** * Creates an OPT Record. This is normally called by SimpleResolver, but can * also be called by a server. * @param payloadSize The size of a packet that can be reassembled on the * sending host. * @param xrcode The value of the extended rcode field. This is the upper * 16 bits of the full rcode. * @param flags Additional message flags. * @param version The EDNS version that this DNS implementation supports. * This should be 0 for dnsjava. * @param options The list of options that comprise the data field. There * are currently no defined options. * @see ExtendedFlags */ public OPTRecord(int payloadSize, int xrcode, int version, int flags, List options) { super(Name.root, Type.OPT, payloadSize, 0); checkU16("payloadSize", payloadSize); checkU8("xrcode", xrcode); checkU8("version", version); checkU16("flags", flags); ttl = ((long)xrcode << 24) + ((long)version << 16) + flags; if (options != null) { this.options = new ArrayList(options); } } /** * Creates an OPT Record with no data. This is normally called by * SimpleResolver, but can also be called by a server. * @param payloadSize The size of a packet that can be reassembled on the * sending host. * @param xrcode The value of the extended rcode field. This is the upper * 16 bits of the full rcode. * @param flags Additional message flags. * @param version The EDNS version that this DNS implementation supports. * This should be 0 for dnsjava. * @see ExtendedFlags */ public OPTRecord(int payloadSize, int xrcode, int version, int flags) { this(payloadSize, xrcode, version, flags, null); } /** * Creates an OPT Record with no data. This is normally called by * SimpleResolver, but can also be called by a server. */ public OPTRecord(int payloadSize, int xrcode, int version) { this(payloadSize, xrcode, version, 0, null); } void rrFromWire(DNSInput in) throws IOException { if (in.remaining() > 0) options = new ArrayList(); while (in.remaining() > 0) { int code = in.readU16(); int len = in.readU16(); byte [] data = in.readByteArray(len); options.add(new Option(code, data)); } } void rdataFromString(Tokenizer st, Name origin) throws IOException { throw st.exception("no text format defined for OPT"); } /** Converts rdata to a String */ String rrToString() { StringBuffer sb = new StringBuffer(); if (options != null) { sb.append(options); sb.append(" "); } sb.append(" ; payload "); sb.append(getPayloadSize()); sb.append(", xrcode "); sb.append(getExtendedRcode()); sb.append(", version "); sb.append(getVersion()); sb.append(", flags "); sb.append(getFlags()); return sb.toString(); } /** Returns the maximum allowed payload size. */ public int getPayloadSize() { return dclass; } /** * Returns the extended Rcode * @see Rcode */ public int getExtendedRcode() { return (int)(ttl >>> 24); } /** Returns the highest supported EDNS version */ public int getVersion() { return (int)((ttl >>> 16) & 0xFF); } /** Returns the EDNS flags */ public int getFlags() { return (int)(ttl & 0xFFFF); } void rrToWire(DNSOutput out, Compression c, boolean canonical) { if (options == null) return; Iterator it = options.iterator(); while (it.hasNext()) { Option opt = (Option) it.next(); out.writeU16(opt.code); out.writeU16(opt.data.length); out.writeByteArray(opt.data); } } /** * Gets all options in the OPTRecord. This returns a list of Options. */ public List getOptions() { if (options == null) return Collections.EMPTY_LIST; return Collections.unmodifiableList(options); } /** * Gets all options in the OPTRecord with a specific code. This returns a * list of byte arrays. */ public List getOptions(int code) { if (options == null) return Collections.EMPTY_LIST; List list = null; for (Iterator it = options.iterator(); it.hasNext(); ) { Option opt = (Option) it.next(); if (opt.code == code) { if (list == null) list = new ArrayList(); list.add(opt.data); } } if (list == null) return Collections.EMPTY_LIST; return list; } }
org/xbill/DNS/OPTRecord.java
// Copyright (c) 1999-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Options - describes Extended DNS (EDNS) properties of a Message. * No specific options are defined other than those specified in the * header. An OPT should be generated by Resolver. * * EDNS is a method to extend the DNS protocol while providing backwards * compatibility and not significantly changing the protocol. This * implementation of EDNS is mostly complete at level 0. * * @see Message * @see Resolver * * @author Brian Wellington */ public class OPTRecord extends Record { public static class Option { public final int code; public final byte [] data; /** * Creates an option with the given option code and data. */ public Option(int code, byte [] data) { this.code = checkU8("option code", code); this.data = data; } public String toString() { return "{" + code + " <" + base16.toString(data) + ">}"; } } private List options; private static List emptyList = Collections.unmodifiableList(new ArrayList()); OPTRecord() {} Record getObject() { return new OPTRecord(); } /** * Creates an OPT Record. This is normally called by SimpleResolver, but can * also be called by a server. * @param payloadSize The size of a packet that can be reassembled on the * sending host. * @param xrcode The value of the extended rcode field. This is the upper * 16 bits of the full rcode. * @param flags Additional message flags. * @param version The EDNS version that this DNS implementation supports. * This should be 0 for dnsjava. * @param options The list of options that comprise the data field. There * are currently no defined options. * @see ExtendedFlags */ public OPTRecord(int payloadSize, int xrcode, int version, int flags, List options) { super(Name.root, Type.OPT, payloadSize, 0); checkU16("payloadSize", payloadSize); checkU8("xrcode", xrcode); checkU8("version", version); checkU16("flags", flags); ttl = ((long)xrcode << 24) + ((long)version << 16) + flags; if (options != null) { this.options = new ArrayList(options); } } /** * Creates an OPT Record with no data. This is normally called by * SimpleResolver, but can also be called by a server. * @param payloadSize The size of a packet that can be reassembled on the * sending host. * @param xrcode The value of the extended rcode field. This is the upper * 16 bits of the full rcode. * @param flags Additional message flags. * @param version The EDNS version that this DNS implementation supports. * This should be 0 for dnsjava. * @see ExtendedFlags */ public OPTRecord(int payloadSize, int xrcode, int version, int flags) { this(payloadSize, xrcode, version, flags, null); } /** * Creates an OPT Record with no data. This is normally called by * SimpleResolver, but can also be called by a server. */ public OPTRecord(int payloadSize, int xrcode, int version) { this(payloadSize, xrcode, version, 0, null); } void rrFromWire(DNSInput in) throws IOException { if (in.remaining() > 0) options = new ArrayList(); while (in.remaining() > 0) { int code = in.readU16(); int len = in.readU16(); byte [] data = in.readByteArray(len); options.add(new Option(code, data)); } } void rdataFromString(Tokenizer st, Name origin) throws IOException { throw st.exception("no text format defined for OPT"); } /** Converts rdata to a String */ String rrToString() { StringBuffer sb = new StringBuffer(); if (options != null) { sb.append(options); sb.append(" "); } sb.append(" ; payload "); sb.append(getPayloadSize()); sb.append(", xrcode "); sb.append(getExtendedRcode()); sb.append(", version "); sb.append(getVersion()); sb.append(", flags "); sb.append(getFlags()); return sb.toString(); } /** Returns the maximum allowed payload size. */ public int getPayloadSize() { return dclass; } /** * Returns the extended Rcode * @see Rcode */ public int getExtendedRcode() { return (int)(ttl >>> 24); } /** Returns the highest supported EDNS version */ public int getVersion() { return (int)((ttl >>> 16) & 0xFF); } /** Returns the EDNS flags */ public int getFlags() { return (int)(ttl & 0xFFFF); } void rrToWire(DNSOutput out, Compression c, boolean canonical) { if (options == null) return; Iterator it = options.iterator(); while (it.hasNext()) { Option opt = (Option) it.next(); out.writeU16(opt.code); out.writeU16(opt.data.length); out.writeByteArray(opt.data); } } /** * Gets all options in the OPTRecord. This returns a list of Options. */ public List getOptions() { if (options == null) return emptyList; return Collections.unmodifiableList(options); } /** * Gets all options in the OPTRecord with a specific code. This returns a * list of byte arrays. */ public List getOptions(int code) { if (options == null) return emptyList; List list = null; for (Iterator it = options.iterator(); it.hasNext(); ) { Option opt = (Option) it.next(); if (opt.code == code) { if (list == null) list = new ArrayList(); list.add(opt.data); } } if (list == null) list = emptyList; return list; } }
Use Collections.EMPTY_LIST.
org/xbill/DNS/OPTRecord.java
Use Collections.EMPTY_LIST.
<ide><path>rg/xbill/DNS/OPTRecord.java <ide> } <ide> <ide> private List options; <del>private static List emptyList = Collections.unmodifiableList(new ArrayList()); <ide> <ide> OPTRecord() {} <ide> <ide> public List <ide> getOptions() { <ide> if (options == null) <del> return emptyList; <add> return Collections.EMPTY_LIST; <ide> return Collections.unmodifiableList(options); <ide> } <ide> <ide> public List <ide> getOptions(int code) { <ide> if (options == null) <del> return emptyList; <add> return Collections.EMPTY_LIST; <ide> List list = null; <ide> for (Iterator it = options.iterator(); it.hasNext(); ) { <ide> Option opt = (Option) it.next(); <ide> } <ide> } <ide> if (list == null) <del> list = emptyList; <add> return Collections.EMPTY_LIST; <ide> return list; <ide> } <ide>
Java
mit
ad6f51905f80ff0e4dbe499a7f89d465a0b68258
0
TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android
/* ChromeCastHttpServer.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.chromecast.core; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.deviceconnect.android.deviceplugin.chromecast.BuildConfig; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import fi.iki.elonen.NanoHTTPD; /** * Chromecast HttpServer クラス. * * <p> * HttpServer機能を提供<br/> * - 選択されたファイルのみ配信する<br/> * </p> * @author NTT DOCOMO, INC. */ public class ChromeCastHttpServer extends NanoHTTPD { /** Local IP Address prefix. */ private static final String PREFIX_LOCAL_IP = "192.168."; enum NetworkStatus { OFF, WIFI, MOBILE, WIMAX, BLUETOOTH, ETHERNET; } /** Logger. */ private final Logger mLogger = Logger.getLogger("chromecast.dplugin"); /** The List of media files. */ private final List<MediaFile> mFileList = new ArrayList<MediaFile>(); private Context mContext; /** * コンストラクタ. * * @param host ipアドレス * @param port ポート番号 */ public ChromeCastHttpServer(final Context context, final String host, final int port) { super(host, port); mContext = context; } /** * クライアントに応答する. * * @param session セッション * @return レスポンス */ public Response serve(final IHTTPSession session) { mLogger.info("Received HTTP request: " + session.getUri()); Map<String, String> header = session.getHeaders(); String uri = session.getUri(); return respond(Collections.unmodifiableMap(header), session, uri); } /** * 指定されたファイルを公開する. * * @param file 公開するファイル * @return 公開用URI */ public String exposeFile(final MediaFile file) { synchronized (mFileList) { mFileList.add(file); } String address = getIpAddress(); if (address == null) { return null; } return "http://" + address + ":" + getListeningPort() + file.getPath(); } /** * クライアントをチェックする. * * @param headers ヘッダー * @return 有効か否か (true: 有効, false: 無効) */ private boolean checkRemote(final Map<String, String> headers) { String remoteAddr = headers.get("remote-addr"); try { InetAddress addr = InetAddress.getByName(remoteAddr); return addr.isSiteLocalAddress(); } catch (UnknownHostException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } return false; } } /** * クライアントへのレスポンスを作成する. * * @param headers ヘッダー * @param session セッション * @param uri ファイルのURI * @return レスポンス */ private Response respond(final Map<String, String> headers, final IHTTPSession session, final String uri) { if (!checkRemote(headers)) { return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, ""); } MediaFile mediaFile = findFile(uri); if (mediaFile == null) { mLogger.info("File not found: URI=" + uri); return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, ""); } mLogger.info("Found File: " + mediaFile.mFile.getAbsolutePath()); Response response = serveFile(uri, headers, mediaFile.mFile, ""); if (response == null) { return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, ""); } return response; } /** * 指定したURIで公開しているファイルを検索する. * * @param uri ファイル公開用URI * @return 検索により見つかったファイル. 見つからなかった場合は<code>null</code> */ private MediaFile findFile(final String uri) { synchronized (mFileList) { for (MediaFile file : mFileList) { mLogger.info(" - " + file.getPath()); if (uri.equals(file.getPath())) { return file; } } } return null; } /** * レスポンスを作成する. * * @param status ステータス * @param mimeType MIMEタイプ * @param message メッセージ (InputStream) * @return レスポンス */ private Response createResponse(final Response.Status status, final String mimeType, final InputStream message) { Response res = new Response(status, mimeType, message); res.addHeader("Accept-Ranges", "bytes"); return res; } /** * レスポンスを作成する. * * @param status ステータス * @param mimeType MIMEタイプ * @param message メッセージ (String) * @return レスポンス */ private Response createResponse(final Response.Status status, final String mimeType, final String message) { Response res = new Response(status, mimeType, message); res.addHeader("Accept-Ranges", "bytes"); return res; } /** * IPアドレスを取得する. * * @return IPアドレス */ private String getIpAddress() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); LinkedList<InetAddress> localAddresses = new LinkedList<InetAddress>(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces .nextElement(); Enumeration<InetAddress> ipAddrs = networkInterface .getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = (InetAddress) ipAddrs.nextElement(); String ipStr = ip.getHostAddress(); mLogger.info("Searching IP Address: Address=" + ipStr + " isLoopback=" + ip.isLoopbackAddress() + " isSiteLocal=" + ip.isSiteLocalAddress()); NetworkStatus status = NetworkStatus.OFF; NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if ( info != null ) { if ( info.isConnected() ) { switch ( info.getType() ) { case ConnectivityManager.TYPE_WIFI: // Wifi status = NetworkStatus.WIFI; break; case ConnectivityManager.TYPE_MOBILE_DUN: // Mobile 3G case ConnectivityManager.TYPE_MOBILE_HIPRI: case ConnectivityManager.TYPE_MOBILE_MMS: case ConnectivityManager.TYPE_MOBILE_SUPL: case ConnectivityManager.TYPE_MOBILE: status = NetworkStatus.MOBILE; break; case ConnectivityManager.TYPE_BLUETOOTH: // Bluetooth status = NetworkStatus.BLUETOOTH; break; case ConnectivityManager.TYPE_ETHERNET: // Ethernet status = NetworkStatus.ETHERNET; break; } } } // ipv6を除外 if (ipStr.indexOf("::") == -1 && (status == NetworkStatus.WIFI || status == NetworkStatus.ETHERNET)) { localAddresses.addFirst(ip); } } } if (localAddresses.size() == 0) { return null; } return localAddresses.get(0).getHostAddress(); } catch (SocketException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; } /** * ファイルのレスポンスを作成する. * * @param uri ファイルのURI * @param header ヘッダー * @param file ファイル * @param mime MIMEタイプ * @return レスポンス */ Response serveFile(final String uri, final Map<String, String> header, final File file, final String mime) { Response res; try { String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode()); long startFrom = 0; long endAt = -1; String range = header.get("range"); if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); try { if (minus > 0) { startFrom = Long.parseLong(range .substring(0, minus)); endAt = Long.parseLong(range.substring(minus + 1)); } } catch (NumberFormatException ignored) { if (BuildConfig.DEBUG) { ignored.printStackTrace(); } } } } long fileLen = file.length(); if (range != null && startFrom >= 0) { if (startFrom >= fileLen) { res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes 0-0/" + fileLen); res.addHeader("ETag", etag); } else { if (endAt < 0) { endAt = fileLen - 1; } long newLen = endAt - startFrom + 1; if (newLen < 0) { newLen = 0; } final long dataLen = newLen; FileInputStream fis = new FileInputStream(file) { @Override public int available() throws IOException { return (int) dataLen; } }; fis.skip(startFrom); res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis); res.addHeader("Content-Length", "" + dataLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader("ETag", etag); } } else { if (etag.equals(header.get("if-none-match"))) { res = createResponse(Response.Status.NOT_MODIFIED, mime, ""); } else { res = createResponse(Response.Status.OK, mime, new FileInputStream(file)); res.addHeader("Content-Length", "" + fileLen); res.addHeader("ETag", etag); } } } catch (IOException ioe) { res = createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, ""); } return res; } }
dConnectDevicePlugin/dConnectDeviceChromeCast/app/src/main/java/org/deviceconnect/android/deviceplugin/chromecast/core/ChromeCastHttpServer.java
/* ChromeCastHttpServer.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.chromecast.core; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.deviceconnect.android.deviceplugin.chromecast.BuildConfig; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import fi.iki.elonen.NanoHTTPD; /** * Chromecast HttpServer クラス. * * <p> * HttpServer機能を提供<br/> * - 選択されたファイルのみ配信する<br/> * </p> * @author NTT DOCOMO, INC. */ public class ChromeCastHttpServer extends NanoHTTPD { /** Local IP Address prefix. */ private static final String PREFIX_LOCAL_IP = "192.168."; enum NetworkStatus { OFF, WIFI, MOBILE, WIMAX, BLUETOOTH, ETHERNET; } /** Logger. */ private final Logger mLogger = Logger.getLogger("chromecast.dplugin"); /** The List of media files. */ private final List<MediaFile> mFileList = new ArrayList<MediaFile>(); private Context mContext; /** * コンストラクタ. * * @param host ipアドレス * @param port ポート番号 */ public ChromeCastHttpServer(final Context context, final String host, final int port) { super(host, port); mContext = context; } /** * クライアントに応答する. * * @param session セッション * @return レスポンス */ public Response serve(final IHTTPSession session) { mLogger.info("Received HTTP request: " + session.getUri()); Map<String, String> header = session.getHeaders(); String uri = session.getUri(); return respond(Collections.unmodifiableMap(header), session, uri); } /** * 指定されたファイルを公開する. * * @param file 公開するファイル * @return 公開用URI */ public String exposeFile(final MediaFile file) { synchronized (mFileList) { mFileList.add(file); } String address = getIpAddress(); if (address == null) { return null; } return "http://" + address + ":" + getListeningPort() + file.getPath(); } /** * クライアントをチェックする. * * @param headers ヘッダー * @return 有効か否か (true: 有効, false: 無効) */ private boolean checkRemote(final Map<String, String> headers) { String remoteAddr = headers.get("remote-addr"); try { InetAddress addr = InetAddress.getByName(remoteAddr); return addr.isSiteLocalAddress(); } catch (UnknownHostException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } return false; } } /** * クライアントへのレスポンスを作成する. * * @param headers ヘッダー * @param session セッション * @param uri ファイルのURI * @return レスポンス */ private Response respond(final Map<String, String> headers, final IHTTPSession session, final String uri) { if (!checkRemote(headers)) { return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, ""); } MediaFile mediaFile = findFile(uri); if (mediaFile == null) { mLogger.info("File not found: URI=" + uri); return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, ""); } mLogger.info("Found File: " + mediaFile.mFile.getAbsolutePath()); Response response = serveFile(uri, headers, mediaFile.mFile, ""); if (response == null) { return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, ""); } return response; } /** * 指定したURIで公開しているファイルを検索する. * * @param uri ファイル公開用URI * @return 検索により見つかったファイル. 見つからなかった場合は<code>null</code> */ private MediaFile findFile(final String uri) { synchronized (mFileList) { for (MediaFile file : mFileList) { mLogger.info(" - " + file.getPath()); if (uri.equals(file.getPath())) { return file; } } } return null; } /** * レスポンスを作成する. * * @param status ステータス * @param mimeType MIMEタイプ * @param message メッセージ (InputStream) * @return レスポンス */ private Response createResponse(final Response.Status status, final String mimeType, final InputStream message) { Response res = new Response(status, mimeType, message); res.addHeader("Accept-Ranges", "bytes"); return res; } /** * レスポンスを作成する. * * @param status ステータス * @param mimeType MIMEタイプ * @param message メッセージ (String) * @return レスポンス */ private Response createResponse(final Response.Status status, final String mimeType, final String message) { Response res = new Response(status, mimeType, message); res.addHeader("Accept-Ranges", "bytes"); return res; } /** * IPアドレスを取得する. * * @return IPアドレス */ private String getIpAddress() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); LinkedList<InetAddress> localAddresses = new LinkedList<InetAddress>(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces .nextElement(); Enumeration<InetAddress> ipAddrs = networkInterface .getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = (InetAddress) ipAddrs.nextElement(); String ipStr = ip.getHostAddress(); mLogger.info("Searching IP Address: Address=" + ipStr + " isLoopback=" + ip.isLoopbackAddress() + " isSiteLocal=" + ip.isSiteLocalAddress()); NetworkStatus status = NetworkStatus.OFF; NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if ( info != null ) { if ( info.isConnected() ) { switch ( info.getType() ) { case ConnectivityManager.TYPE_WIFI: // Wifi status = NetworkStatus.WIFI; break; case ConnectivityManager.TYPE_MOBILE_DUN: // Mobile 3G case ConnectivityManager.TYPE_MOBILE_HIPRI: case ConnectivityManager.TYPE_MOBILE_MMS: case ConnectivityManager.TYPE_MOBILE_SUPL: case ConnectivityManager.TYPE_MOBILE: status = NetworkStatus.MOBILE; break; case ConnectivityManager.TYPE_BLUETOOTH: // Bluetooth status = NetworkStatus.BLUETOOTH; break; case ConnectivityManager.TYPE_ETHERNET: // Ethernet status = NetworkStatus.ETHERNET; break; } } } if (status == NetworkStatus.WIFI || status == NetworkStatus.ETHERNET) { localAddresses.addFirst(ip); } } } if (localAddresses.size() == 0) { return null; } return localAddresses.get(0).getHostAddress(); } catch (SocketException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; } /** * ファイルのレスポンスを作成する. * * @param uri ファイルのURI * @param header ヘッダー * @param file ファイル * @param mime MIMEタイプ * @return レスポンス */ Response serveFile(final String uri, final Map<String, String> header, final File file, final String mime) { Response res; try { String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode()); long startFrom = 0; long endAt = -1; String range = header.get("range"); if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); try { if (minus > 0) { startFrom = Long.parseLong(range .substring(0, minus)); endAt = Long.parseLong(range.substring(minus + 1)); } } catch (NumberFormatException ignored) { if (BuildConfig.DEBUG) { ignored.printStackTrace(); } } } } long fileLen = file.length(); if (range != null && startFrom >= 0) { if (startFrom >= fileLen) { res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes 0-0/" + fileLen); res.addHeader("ETag", etag); } else { if (endAt < 0) { endAt = fileLen - 1; } long newLen = endAt - startFrom + 1; if (newLen < 0) { newLen = 0; } final long dataLen = newLen; FileInputStream fis = new FileInputStream(file) { @Override public int available() throws IOException { return (int) dataLen; } }; fis.skip(startFrom); res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis); res.addHeader("Content-Length", "" + dataLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader("ETag", etag); } } else { if (etag.equals(header.get("if-none-match"))) { res = createResponse(Response.Status.NOT_MODIFIED, mime, ""); } else { res = createResponse(Response.Status.OK, mime, new FileInputStream(file)); res.addHeader("Content-Length", "" + fileLen); res.addHeader("ETag", etag); } } } catch (IOException ioe) { res = createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, ""); } return res; } }
IPv6の除外。
dConnectDevicePlugin/dConnectDeviceChromeCast/app/src/main/java/org/deviceconnect/android/deviceplugin/chromecast/core/ChromeCastHttpServer.java
IPv6の除外。
<ide><path>ConnectDevicePlugin/dConnectDeviceChromeCast/app/src/main/java/org/deviceconnect/android/deviceplugin/chromecast/core/ChromeCastHttpServer.java <ide> } <ide> } <ide> } <del> if (status == NetworkStatus.WIFI <del> || status == NetworkStatus.ETHERNET) { <add> // ipv6を除外 <add> if (ipStr.indexOf("::") == -1 && (status == NetworkStatus.WIFI <add> || status == NetworkStatus.ETHERNET)) { <ide> localAddresses.addFirst(ip); <ide> } <ide> }
Java
mit
4e88010fef92f6f228e57e27cb8c8e71aa2139b4
0
jameslawler/android-ten-seven
package com.jameslawler.tenseven; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; import com.trello.rxlifecycle.components.RxActivity; import java.util.Calendar; import java.util.concurrent.TimeUnit; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends RxActivity { @Bind(R.id.countdown) TextView countdownTextBox; @Bind(R.id.countdownLabel) TextView countdownLabel; @Bind(R.id.countdownContainer) LinearLayout countdownContainer; @BindString(R.string.countdown_label_walk) String countdownLabelWalk; @BindString(R.string.countdown_label_run) String countdownLabelRun; @BindString(R.string.countdown_label_wait) String countdownLabelWait; Countdown previousCountdown; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @Override protected void onResume() { super.onResume(); Observable.interval(1, TimeUnit.SECONDS) .compose(bindToLifecycle()) .subscribeOn(Schedulers.io()) .map(l -> Countdown.getInstance().Update(Calendar.getInstance())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(c -> displayCountdown(c)); } private void displayCountdown(Countdown countdown) { countdownTextBox.setText(countdown.TimeLeft); if (previousCountdown == null || countdown.State != previousCountdown.State) { previousCountdown = countdown; switch (countdown.State) { case Walk: countdownContainer.setBackgroundResource(R.color.walk); countdownLabel.setText(countdownLabelWalk); break; case Run: countdownContainer.setBackgroundResource(R.color.run); countdownLabel.setText(countdownLabelRun); break; default: countdownContainer.setBackgroundResource(R.color.wait); countdownLabel.setText(countdownLabelWait); } } } }
app/src/main/java/com/jameslawler/tenseven/MainActivity.java
package com.jameslawler.tenseven; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; import com.trello.rxlifecycle.components.RxActivity; import java.util.Calendar; import java.util.concurrent.TimeUnit; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends RxActivity { @Bind(R.id.countdown) TextView countdownTextBox; @Bind(R.id.countdownLabel) TextView countdownLabel; @Bind(R.id.countdownContainer) LinearLayout countdownContainer; @BindString(R.string.countdown_label_walk) String countdownLabelWalk; @BindString(R.string.countdown_label_run) String countdownLabelRun; @BindString(R.string.countdown_label_wait) String countdownLabelWait; Countdown previousCountdown; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @Override protected void onResume() { super.onResume(); Observable.interval(1, TimeUnit.SECONDS) .compose(bindToLifecycle()) .subscribeOn(Schedulers.io()) .map(l -> Countdown.getInstance().Update(Calendar.getInstance())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(c -> displayCountdown(c)); } private void displayCountdown(Countdown countdown) { countdownTextBox.setText(countdown.TimeLeft); if (previousCountdown == null || countdown.State != previousCountdown.State) { previousCountdown = countdown; switch (countdown.State) { case Walk: countdownContainer.setBackgroundResource(R.color.walk); countdownLabel.setText(countdownLabelWalk); break; case Run: countdownContainer.setBackgroundResource(R.color.run); countdownLabel.setText(countdownLabelRun); break; default: countdownContainer.setBackgroundResource(R.color.wait); countdownLabel.setText(countdownLabelWait); } } } }
Remove unused references
app/src/main/java/com/jameslawler/tenseven/MainActivity.java
Remove unused references
<ide><path>pp/src/main/java/com/jameslawler/tenseven/MainActivity.java <ide> package com.jameslawler.tenseven; <ide> <del>import android.content.IntentFilter; <del>import android.net.ConnectivityManager; <ide> import android.os.Bundle; <ide> import android.widget.LinearLayout; <ide> import android.widget.TextView;
Java
apache-2.0
0e7405cef208195866dda5eb35e2e8c9e5da4099
0
eug48/hapi-fhir,Gaduo/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,botunge/hapi-fhir,jamesagnew/hapi-fhir,botunge/hapi-fhir,Gaduo/hapi-fhir,eug48/hapi-fhir,Gaduo/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,botunge/hapi-fhir,aemay2/hapi-fhir,botunge/hapi-fhir,SingingTree/hapi-fhir,Gaduo/hapi-fhir,aemay2/hapi-fhir,eug48/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,eug48/hapi-fhir,eug48/hapi-fhir,SingingTree/hapi-fhir,Gaduo/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,botunge/hapi-fhir
package ca.uhn.fhir.i18n; import static org.apache.commons.lang3.StringUtils.isNotBlank; /* * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2016 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; /** * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with caution */ public class HapiLocalizer { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(HapiLocalizer.class); private List<ResourceBundle> myBundle = new ArrayList<ResourceBundle>(); private final Map<String, MessageFormat> myKeyToMessageFormat = new ConcurrentHashMap<String, MessageFormat>(); public HapiLocalizer() { this(HapiLocalizer.class.getPackage().getName() + ".hapi-messages"); } public HapiLocalizer(String... theBundleNames) { for (String nextName : theBundleNames) { myBundle.add(ResourceBundle.getBundle(nextName)); } } private String findFormatString(String theQualifiedKey) { String formatString = null; for (ResourceBundle nextBundle : myBundle) { if (nextBundle.containsKey(theQualifiedKey)) { formatString = nextBundle.getString(theQualifiedKey); } if (isNotBlank(formatString)) { break; } } if (formatString == null) { ourLog.warn("Unknown localization key: {}", theQualifiedKey); formatString = "!MESSAGE!"; } return formatString; } public String getMessage(Class<?> theType, String theKey, Object... theParameters) { return getMessage(theType.getName() + '.' + theKey, theParameters); } public String getMessage(String theQualifiedKey, Object... theParameters) { if (theParameters != null && theParameters.length > 0) { MessageFormat format = myKeyToMessageFormat.get(theQualifiedKey); if (format != null) { return format.format(theParameters).toString(); } String formatString = findFormatString(theQualifiedKey); format = new MessageFormat(formatString.trim()); myKeyToMessageFormat.put(theQualifiedKey, format); return format.format(theParameters).toString(); } else { String retVal = findFormatString(theQualifiedKey); return retVal; } } }
hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java
package ca.uhn.fhir.i18n; import static org.apache.commons.lang3.StringUtils.isNotBlank; /* * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2016 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; /** * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with caution */ public class HapiLocalizer { private List<ResourceBundle> myBundle = new ArrayList<ResourceBundle>(); private final Map<String, MessageFormat> myKeyToMessageFormat = new ConcurrentHashMap<String, MessageFormat>(); public HapiLocalizer() { this(HapiLocalizer.class.getPackage().getName() + ".hapi-messages"); } public HapiLocalizer(String... theBundleNames) { for (String nextName : theBundleNames) { myBundle.add(ResourceBundle.getBundle(nextName)); } } public String getMessage(Class<?> theType, String theKey, Object... theParameters) { return getMessage(theType.getName() + '.' + theKey, theParameters); } public String getMessage(String theQualifiedKey, Object... theParameters) { if (theParameters != null && theParameters.length > 0) { MessageFormat format = myKeyToMessageFormat.get(theQualifiedKey); if (format != null) { return format.format(theParameters).toString(); } String formatString = findFormatString(theQualifiedKey); format = new MessageFormat(formatString.trim()); myKeyToMessageFormat.put(theQualifiedKey, format); return format.format(theParameters).toString(); } else { String retVal = findFormatString(theQualifiedKey); return retVal; } } private String findFormatString(String theQualifiedKey) { String formatString = null; for (ResourceBundle nextBundle : myBundle) { if (nextBundle.containsKey(theQualifiedKey)) { formatString = nextBundle.getString(theQualifiedKey); } if (isNotBlank(formatString)) { break; } } if (formatString == null) { formatString = "!MESSAGE!"; } return formatString; } }
Better error message when localizer can't find key
hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java
Better error message when localizer can't find key
<ide><path>api-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java <ide> */ <ide> public class HapiLocalizer { <ide> <add> private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(HapiLocalizer.class); <ide> private List<ResourceBundle> myBundle = new ArrayList<ResourceBundle>(); <add> <ide> private final Map<String, MessageFormat> myKeyToMessageFormat = new ConcurrentHashMap<String, MessageFormat>(); <ide> <ide> public HapiLocalizer() { <ide> for (String nextName : theBundleNames) { <ide> myBundle.add(ResourceBundle.getBundle(nextName)); <ide> } <add> } <add> <add> private String findFormatString(String theQualifiedKey) { <add> String formatString = null; <add> for (ResourceBundle nextBundle : myBundle) { <add> if (nextBundle.containsKey(theQualifiedKey)) { <add> formatString = nextBundle.getString(theQualifiedKey); <add> } <add> if (isNotBlank(formatString)) { <add> break; <add> } <add> } <add> <add> if (formatString == null) { <add> ourLog.warn("Unknown localization key: {}", theQualifiedKey); <add> formatString = "!MESSAGE!"; <add> } <add> return formatString; <ide> } <ide> <ide> public String getMessage(Class<?> theType, String theKey, Object... theParameters) { <ide> return retVal; <ide> } <ide> } <del> <del> private String findFormatString(String theQualifiedKey) { <del> String formatString = null; <del> for (ResourceBundle nextBundle : myBundle) { <del> if (nextBundle.containsKey(theQualifiedKey)) { <del> formatString = nextBundle.getString(theQualifiedKey); <del> } <del> if (isNotBlank(formatString)) { <del> break; <del> } <del> } <del> <del> if (formatString == null) { <del> formatString = "!MESSAGE!"; <del> } <del> return formatString; <del> } <del> <ide> }
Java
apache-2.0
db6ab84891b3fdd1ecf24c62f048bc444d7035c3
0
ouit0408/sakai,willkara/sakai,ouit0408/sakai,willkara/sakai,OpenCollabZA/sakai,Fudan-University/sakai,ouit0408/sakai,joserabal/sakai,Fudan-University/sakai,Fudan-University/sakai,ouit0408/sakai,frasese/sakai,ouit0408/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,joserabal/sakai,joserabal/sakai,rodriguezdevera/sakai,Fudan-University/sakai,willkara/sakai,willkara/sakai,OpenCollabZA/sakai,frasese/sakai,rodriguezdevera/sakai,frasese/sakai,OpenCollabZA/sakai,frasese/sakai,Fudan-University/sakai,ouit0408/sakai,Fudan-University/sakai,willkara/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,joserabal/sakai,rodriguezdevera/sakai,willkara/sakai,willkara/sakai,frasese/sakai,rodriguezdevera/sakai,ouit0408/sakai,frasese/sakai,ouit0408/sakai,frasese/sakai,frasese/sakai,OpenCollabZA/sakai,Fudan-University/sakai,joserabal/sakai,willkara/sakai,Fudan-University/sakai,joserabal/sakai,rodriguezdevera/sakai,joserabal/sakai,OpenCollabZA/sakai,joserabal/sakai,OpenCollabZA/sakai
package org.sakaiproject.tool.assessment.ui.listener.evaluation; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.TreeSet; import javax.faces.component.html.HtmlSelectOneMenu; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.event.ValueChangeEvent; import javax.faces.event.ValueChangeListener; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import org.hibernate.Hibernate; import org.sakaiproject.tool.assessment.api.SamigoApiFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingComparatorByScoreAndUniqueIdentifier; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentBaseIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemMetaDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.PublishedItemService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.Phase; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.PhaseStatus; import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.ExportResponsesBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramBarBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramQuestionScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.ItemBarBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.QuestionScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.util.ResourceLoader; /** * <p> * This handles the selection of the Histogram Aggregate Statistics. * </p> * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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. * * @version $Id$ */ public class HistogramListener implements ActionListener, ValueChangeListener { private static Logger log = LoggerFactory.getLogger(HistogramListener.class); //private static BeanSort bs; //private static ContextUtil cu; //private static EvaluationListenerUtil util; /** * Standard process action method. * @param ae ActionEvent * @throws AbortProcessingException */ public void processAction(ActionEvent ae) throws AbortProcessingException { log.debug("HistogramListener.processAction()"); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); if (!histogramScores(bean, totalBean)) { String publishedId = totalBean.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } log.error("Error getting statistics for assessment with published id = " + publishedId); FacesContext context = FacesContext.getCurrentInstance(); // reset histogramScoresBean, otherwise the previous assessment viewed is displayed. // note that createValueBinding seems to be deprecated and replaced by a new method in 1.2. Might need to modify this later FacesContext.getCurrentInstance().getApplication().createValueBinding("#{histogramScores}").setValue(FacesContext.getCurrentInstance(), null ); return ; } } /** * Process a value change. */ public void processValueChange(ValueChangeEvent event) { if(!HtmlSelectOneMenu.class.isInstance(event.getSource()) || event.getNewValue() == null || event.getNewValue().equals(event.getOldValue())){ return; } HtmlSelectOneMenu selectOneMenu = HtmlSelectOneMenu.class.cast(event.getSource()); if(selectOneMenu.getId() != null && selectOneMenu.getId().startsWith("allSubmissions")){ processAllSubmissionsChange(event); } } public void processAllSubmissionsChange(ValueChangeEvent event) { TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores"); String selectedvalue= (String) event.getNewValue(); if ((selectedvalue!=null) && (!selectedvalue.equals("")) ){ log.debug("changed submission pulldown "); bean.setAllSubmissions(selectedvalue); // changed for histogram score bean totalBean.setAllSubmissions(selectedvalue); // changed for total score bean questionBean.setAllSubmissions(selectedvalue); // changed for Question score bean } if (!histogramScores(bean, totalBean)) { String publishedId = totalBean.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } log.error("Error getting statistics for assessment with published id = " + publishedId); FacesContext context = FacesContext.getCurrentInstance(); FacesContext.getCurrentInstance().getApplication().createValueBinding( "#{histogramScores}").setValue(FacesContext.getCurrentInstance(), null ); return ; } } /** * Calculate the detailed statistics * * This will populate the HistogramScoresBean with the data associated with the * particular versioned assessment based on the publishedId. * * Some of this code will change when we move this to Hibernate persistence. * @param publishedId String * @param histogramScores TotalScoresBean * @return boolean true if successful */ public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) { DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery"); String publishedId = totalScores.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } String actionString = ContextUtil.lookupParam("actionString"); // See if this can fix SAK-16437 if (actionString != null && !actionString.equals("reviewAssessment")){ // Shouldn't come to here. The action should either be null or reviewAssessment. // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message. log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = " + AgentFacade.getAgentString()); } ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); String assessmentName = ""; histogramScores.clearLowerQuartileStudents(); histogramScores.clearUpperQuartileStudents(); String which = histogramScores.getAllSubmissions(); if (which == null && totalScores.getAllSubmissions() != null) { // use totalscore's selection which = totalScores.getAllSubmissions(); histogramScores.setAllSubmissions(which); // changed submission pulldown } histogramScores.setItemId(ContextUtil.lookupParam("itemId")); histogramScores.setHasNav(ContextUtil.lookupParam("hasNav")); GradingService delegate = new GradingService(); PublishedAssessmentService pubService = new PublishedAssessmentService(); List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which); //set the ItemGradingData manually here. or we cannot //retrieve it later. for(AssessmentGradingData agd: allscores){ agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId()))); } if (allscores.isEmpty()) { // Similar case in Bug 1537, but clicking Statistics link instead of assignment title. // Therefore, redirect the the same page. delivery.setOutcome("reviewAssessmentError"); delivery.setActionString(actionString); return true; } histogramScores.setPublishedId(publishedId); int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER; String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent"); if (isFromStudent != null && "true".equals(isFromStudent)) { callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT; } // get the Map of all users(keyed on userid) belong to the selected sections // now we only include scores of users belong to the selected sections Map useridMap = null; ArrayList scores = new ArrayList(); // only do section filter if it's published to authenticated users if (totalScores.getReleaseToAnonymous()) { scores.addAll(allscores); } else { useridMap = totalScores.getUserIdMap(callerName); Iterator allscores_iter = allscores.iterator(); while (allscores_iter.hasNext()) { AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next(); String agentid = data.getAgentId(); if (useridMap.containsKey(agentid)) { scores.add(data); } } } Iterator iter = scores.iterator(); //log.info("Has this many agents: " + scores.size()); if (!iter.hasNext()){ log.info("Students who have submitted may have been removed from this site"); return false; } // here scores contain AssessmentGradingData Map assessmentMap = getAssessmentStatisticsMap(scores); /* * find students in upper and lower quartiles * of assessment scores */ ArrayList submissionsSortedForDiscrim = new ArrayList(scores); boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue(); Collections.sort(submissionsSortedForDiscrim, new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous)); int numSubmissions = scores.size(); //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded int percent27 = numSubmissions*27/100; // rounded down if (percent27 == 0) percent27 = 1; for (int i=0; i<percent27; i++) { histogramScores.addToLowerQuartileStudents(((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId()); histogramScores.addToUpperQuartileStudents(((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions-1-i)).getAgentId()); } PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false); if (pub != null) { if (actionString != null && actionString.equals("reviewAssessment")){ if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) { // Bug 1547: If this is during review and the assessment is retracted for edit now, // set the outcome to isRetractedForEdit2 error page. delivery.setOutcome("isRetractedForEdit2"); delivery.setActionString(actionString); return true; } else { delivery.setOutcome("histogramScores"); delivery.setSecureDeliveryHTMLFragment( "" ); delivery.setBlockDelivery( false ); SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance().getSecureDeliveryServiceAPI(); if ( secureDelivery.isSecureDeliveryAvaliable() ) { String moduleId = pub.getAssessmentMetaDataByLabel( SecureDeliveryServiceAPI.MODULE_KEY ); if ( moduleId != null && ! SecureDeliveryServiceAPI.NONE_ID.equals( moduleId ) ) { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW, pub, request ); delivery.setSecureDeliveryHTMLFragment( secureDelivery.getHTMLFragment(moduleId, pub, request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale() ) ); if ( PhaseStatus.FAILURE == status ) { delivery.setOutcome( "secureDeliveryError" ); delivery.setActionString(actionString); delivery.setBlockDelivery( true ); return true; } } } } } boolean showObjectivesColumn = Boolean.parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS)); Map<String, Double> objectivesCorrect = new HashMap<String, Double>(); Map<String, Integer> objectivesCounter = new HashMap<String, Integer>(); Map<String, Double> keywordsCorrect = new HashMap<String, Double>(); Map<String, Integer> keywordsCounter = new HashMap<String, Integer>(); assessmentName = pub.getTitle(); List<? extends SectionDataIfc> parts = pub.getSectionArraySorted(); histogramScores.setAssesmentParts((List<PublishedSectionData>)parts); ArrayList info = new ArrayList(); Iterator partsIter = parts.iterator(); int secseq = 1; double totalpossible = 0; boolean hasRandompart = false; boolean isRandompart = false; String poolName = null; HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which); HashMap itemScores = new HashMap(); if (totalScores.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users itemScores.putAll(itemScoresMap); } else { if (useridMap == null) { useridMap = totalScores.getUserIdMap(callerName); } for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Long itemId = (Long) entry.getKey(); ArrayList itemScoresList = (ArrayList) entry.getValue(); ArrayList filteredItemScoresList = new ArrayList(); Iterator itemScoresIter = itemScoresList.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (itemScoresIter.hasNext()) { ItemGradingData idata = (ItemGradingData) itemScoresIter.next(); String agentid = idata.getAgentId(); if (useridMap.containsKey(agentid)) { filteredItemScoresList.add(idata); } } itemScores.put(itemId, filteredItemScoresList); } } // Iterate through the assessment parts while (partsIter.hasNext()) { SectionDataIfc section = (SectionDataIfc) partsIter.next(); String authortype = section .getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE); try{ if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL .equals(Integer.valueOf(authortype))) { hasRandompart = true; isRandompart = true; poolName = section .getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW); } else { isRandompart = false; poolName = null; } }catch(NumberFormatException e){ isRandompart = false; poolName = null; } if (section.getSequence() == null) section.setSequence(Integer.valueOf(secseq++)); String title = rb.getString("part") + " " + section.getSequence().toString(); title += ", " + rb.getString("question") + " "; List<ItemDataIfc> itemset = section.getItemArraySortedForGrading(); int seq = 1; Iterator<ItemDataIfc> itemsIter = itemset.iterator(); // Iterate through the assessment questions (items) while (itemsIter.hasNext()) { HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean(); questionScores.setNumberOfParts(parts.size()); //if this part is a randompart , then set randompart = true questionScores.setRandomType(isRandompart); questionScores.setPoolName(poolName); ItemDataIfc item = itemsIter.next(); if (showObjectivesColumn) { String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE); questionScores.setObjectives(obj); String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD); questionScores.setKeywords(key); } //String type = delegate.getTextForId(item.getTypeId()); String type = getType(item.getTypeId().intValue()); if (item.getSequence() == null) item.setSequence(Integer.valueOf(seq++)); questionScores.setPartNumber( section.getSequence().toString()); //set the question label depending on random pools and parts if(questionScores.getRandomType() && poolName != null){ if(questionScores.getNumberOfParts() > 1){ questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null)); }else{ questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null)); } }else{ if(questionScores.getNumberOfParts() > 1){ questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null)); }else{ questionScores.setQuestionLabelFormat(rb.getString("label_question", null)); } } questionScores.setQuestionNumber( item.getSequence().toString()); questionScores.setItemId(item.getItemId()); questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")"); if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question questionScores.setQuestionText(item.getLeadInText()); } else { questionScores.setQuestionText(item.getText()); } questionScores.setQuestionType(item.getTypeId().toString()); //totalpossible = totalpossible + item.getScore().doubleValue(); //ArrayList responses = null; //for each question (item) in the published assessment's current part/section determineResults(pub, questionScores, (ArrayList) itemScores .get(item.getItemId())); questionScores.setTotalScore(item.getScore().toString()); questionScores.setN(""+numSubmissions); questionScores.setItemId(item.getItemId()); Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect(); Set studentsResponded = questionScores.getStudentsResponded(); if (studentsWithAllCorrect == null || studentsResponded == null || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) { questionScores.setPercentCorrectFromUpperQuartileStudents("0"); questionScores.setPercentCorrectFromLowerQuartileStudents("0"); questionScores.setDiscrimination("0.0"); } else { int percent27ForThisQuestion = percent27; Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet(); Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet(); if(isRandompart){ //we need to calculate the 27% upper and lower //per question for the people that actually answered //this question. upperQuartileStudents = new HashSet<String>(); lowerQuartileStudents = new HashSet<String>(); percent27ForThisQuestion = questionScores.getNumResponses()*27/100; if (percent27ForThisQuestion == 0) percent27ForThisQuestion = 1; if(questionScores.getNumResponses() != 0){ //need to only get gradings for students that answered this question List<AssessmentGradingData> filteredGradings = filterGradingData(submissionsSortedForDiscrim, questionScores.getItemId()); // SAM-2228: loop control issues because of unsynchronized collection access int filteredGradingsSize = filteredGradings.size(); percent27ForThisQuestion = filteredGradingsSize*27/100; for (int i = 0; i < percent27ForThisQuestion; i++) { lowerQuartileStudents.add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId()); // upperQuartileStudents.add(((AssessmentGradingData) filteredGradings.get(filteredGradingsSize-1-i)).getAgentId()); } } } if(questionScores.getNumResponses() != 0){ int numStudentsWithAllCorrectFromUpperQuartile = 0; int numStudentsWithAllCorrectFromLowerQuartile = 0; Iterator studentsIter = studentsWithAllCorrect.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (upperQuartileStudents.contains(agentId)) { numStudentsWithAllCorrectFromUpperQuartile++; } if (lowerQuartileStudents.contains(agentId)) { numStudentsWithAllCorrectFromLowerQuartile++; } } double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile / (double) percent27ForThisQuestion) * 100d; double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile / (double) percent27ForThisQuestion) * 100d; questionScores.setPercentCorrectFromUpperQuartileStudents( Integer.toString((int) percentCorrectFromUpperQuartileStudents)); questionScores.setPercentCorrectFromLowerQuartileStudents( Integer.toString((int) percentCorrectFromLowerQuartileStudents)); double discrimination = ((double)numStudentsWithAllCorrectFromUpperQuartile - (double)numStudentsWithAllCorrectFromLowerQuartile)/(double)percent27ForThisQuestion ; // round to 2 decimals if (discrimination > 999999 || discrimination < -999999) { questionScores.setDiscrimination("NaN"); } else { discrimination = ((int) (discrimination*100.00d)) / 100.00d; questionScores.setDiscrimination(Double.toString(discrimination)); } }else{ questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na")); questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na")); questionScores.setDiscrimination(rbEval.getString("na")); } } info.add(questionScores); } // end-while - items totalpossible = pub.getTotalScore().doubleValue(); } // end-while - parts histogramScores.setInfo(info); histogramScores.setRandomType(hasRandompart); int maxNumOfAnswers = 0; List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>(); Iterator infoIter = info.iterator(); while (infoIter.hasNext()) { HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean)infoIter.next(); if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString()) || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString()) || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()) || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString()) || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString()) || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString()) || questionScores.getQuestionType().equals("16") ) { questionScores.setShowIndividualAnswersInDetailedStatistics(true); detailedStatistics.add(questionScores); if (questionScores.getHistogramBars() != null) { maxNumOfAnswers = questionScores.getHistogramBars().length >maxNumOfAnswers ? questionScores.getHistogramBars().length : maxNumOfAnswers; } } if (showObjectivesColumn) { // Get the percentage correct by objective String obj = questionScores.getObjectives(); if (obj != null && !"".equals(obj)) { String[] objs = obj.split(","); for (int i=0; i < objs.length; i++) { // SAM-2508 set a default value to avoid the NumberFormatException issues Double pctCorrect = 0.0d; Double newAvg = 0.0d; int divisor = 1; try { if (questionScores.getPercentCorrect() != null && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) { pctCorrect = Double.parseDouble(questionScores.getPercentCorrect()); } } catch (NumberFormatException nfe) { log.error("NFE when looking at metadata and objectives", nfe); } if (objectivesCorrect.get(objs[i]) != null) { Double objCorrect = objectivesCorrect.get(objs[i]); divisor = objCorrect.intValue() + 1; newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); } else { newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue(); } objectivesCounter.put(objs[i], divisor); objectivesCorrect.put(objs[i], newAvg); } } // Get the percentage correct by keyword String key = questionScores.getKeywords(); if (key != null && !"".equals(key)) { String [] keys = key.split(","); for (int i=0; i < keys.length; i++) { if (keywordsCorrect.get(keys[i]) != null) { int divisor = keywordsCounter.get(keys[i]) + 1; Double newAvg = keywordsCorrect.get(keys[i]) + ( (Double.parseDouble(questionScores.getPercentCorrect()) - keywordsCorrect.get(keys[i]) ) / divisor); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); keywordsCounter.put(keys[i], divisor); keywordsCorrect.put(keys[i], newAvg); } else { Double newAvg = Double.parseDouble(questionScores.getPercentCorrect()); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); keywordsCounter.put(keys[i], 1); keywordsCorrect.put(keys[i], newAvg); } } } } //i.e. for EMI questions we add detailed stats for the whole //question as well as for the sub-questions if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) ) { questionScores.setShowIndividualAnswersInDetailedStatistics(false); detailedStatistics.addAll(questionScores.getInfo()); Iterator subInfoIter = questionScores.getInfo().iterator(); while (subInfoIter.hasNext()) { HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter.next(); if (subQuestionScores.getHistogramBars() != null) { subQuestionScores.setN(questionScores.getN()); maxNumOfAnswers = subQuestionScores.getHistogramBars().length >maxNumOfAnswers ? subQuestionScores.getHistogramBars().length : maxNumOfAnswers; } } /* Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId()); if (numberOfStudentsWithZeroAnswers == null) { questionScores.setNumberOfStudentsWithZeroAnswers(0); } else { questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() ); } */ } } //VULA-1948: sort the detailedStatistics list by Question Label sortQuestionScoresByLabel(detailedStatistics); histogramScores.setDetailedStatistics(detailedStatistics); histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers); histogramScores.setShowObjectivesColumn(showObjectivesColumn); if (showObjectivesColumn) { List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(objectivesCorrect.entrySet()); Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() { public int compare(Entry<String, Double> e1, Entry<String, Double> e2) { return e1.getKey().compareTo(e2.getKey()); } }); histogramScores.setObjectives(objectivesList); List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(keywordsCorrect.entrySet()); Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() { public int compare(Entry<String, Double> e1, Entry<String, Double> e2) { return e1.getKey().compareTo(e2.getKey()); } }); histogramScores.setKeywords(keywordsList); } // test to see if it gets back empty map if (assessmentMap.isEmpty()) { histogramScores.setNumResponses(0); } try { BeanUtils.populate(histogramScores, assessmentMap); // quartiles don't seem to be working, workaround histogramScores.setQ1((String) assessmentMap.get("q1")); histogramScores.setQ2((String) assessmentMap.get("q2")); histogramScores.setQ3((String) assessmentMap.get("q3")); histogramScores.setQ4((String) assessmentMap.get("q4")); histogramScores.setTotalScore((String) assessmentMap .get("totalScore")); histogramScores.setTotalPossibleScore(Double .toString(totalpossible)); HistogramBarBean[] bars = new HistogramBarBean[histogramScores .getColumnHeight().length]; for (int i = 0; i < histogramScores.getColumnHeight().length; i++) { bars[i] = new HistogramBarBean(); bars[i] .setColumnHeight(Integer .toString(histogramScores .getColumnHeight()[i])); bars[i].setNumStudents(histogramScores .getNumStudentCollection()[i]); bars[i].setRangeInfo(histogramScores .getRangeCollection()[i]); //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]); } histogramScores.setHistogramBars(bars); /////////////////////////////////////////////////////////// // START DEBUGGING /* log.info("TESTING ASSESSMENT MAP"); log.info("assessmentMap: =>"); log.info(assessmentMap); log.info("--------------------------------------------"); log.info("TESTING TOTALS HISTOGRAM FORM"); log.info( "HistogramScoresForm Form: =>\n" + "bean.getMean()=" + bean.getMean() + "\n" + "bean.getColumnHeight()[0] (first elem)=" + bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" + bean.getInterval() + "\n" + "bean.getLowerQuartile()=" + bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" + bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() + "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" + "bean.getNumResponses()=" + bean.getNumResponses() + "\n" + "bean.getNumStudentCollection()=" + bean.getNumStudentCollection() + "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" + bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" + "bean.getQ4()=" + bean.getQ4()); log.info("--------------------------------------------"); */ // END DEBUGGING CODE /////////////////////////////////////////////////////////// } catch (IllegalAccessException e) { log.warn("IllegalAccessException: unable to populate bean" + e); } catch (InvocationTargetException e) { log.warn("InvocationTargetException: unable to populate bean" + e); } histogramScores.setAssessmentName(assessmentName); } else { log.error("pub is null. publishedId = " + publishedId); return false; } return true; } /** * For each question (item) in the published assessment's current part/section * determine the results by calculating statistics for whole question or * individual answers depending on the question type * @param pub * @param qbean * @param itemScores */ private void determineResults(PublishedAssessmentIfc pub, HistogramQuestionScoresBean qbean, ArrayList<ItemGradingData> itemScores) { if (itemScores == null) itemScores = new ArrayList<ItemGradingData>(); int responses = 0; Set<Long> assessmentGradingIds = new HashSet<Long>(); int numStudentsWithZeroAnswers = 0; for (ItemGradingData itemGradingData: itemScores) { //only count the unique questions answers if(!assessmentGradingIds.contains(itemGradingData.getAssessmentGradingId())){ responses++; assessmentGradingIds.add(itemGradingData.getAssessmentGradingId()); if (itemGradingData.getSubmittedDate() == null) { numStudentsWithZeroAnswers++; } } } qbean.setNumResponses(responses); qbean.setNumberOfStudentsWithZeroAnswers(numStudentsWithZeroAnswers); if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString()) || // mcsc qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString()) || // mcmcms qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString()) || // mcmcss qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString()) || // mc survey qbean.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString()) || // tf qbean.getQuestionType().equals(TypeIfc.MATCHING.toString()) || // matching qbean.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()) || // Fill in the blank qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) || // Extended Matching Items qbean.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString()) || // Numeric Response qbean.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString()) || // CALCULATED_QUESTION qbean.getQuestionType().equals(TypeIfc.IMAGEMAP_QUESTION.toString()) || // IMAGEMAP_QUESTION qbean.getQuestionType().equals(TypeIfc.MATRIX_CHOICES_SURVEY.toString())) // matrix survey doAnswerStatistics(pub, qbean, itemScores); if (qbean.getQuestionType().equals(TypeIfc.ESSAY_QUESTION.toString()) || // essay qbean.getQuestionType().equals(TypeIfc.FILE_UPLOAD.toString()) || // file upload qbean.getQuestionType().equals(TypeIfc.AUDIO_RECORDING.toString())) // audio recording doScoreStatistics(qbean, itemScores); } /** * For each question where statistics are required for seperate answers, * this method calculates the answer statistics by calling a different * getXXXScores() method for each question type. * @param pub * @param qbean * @param scores */ private void doAnswerStatistics(PublishedAssessmentIfc pub, HistogramQuestionScoresBean qbean, List<ItemGradingData> scores) { // Don't return here. This will cause questions to be displayed inconsistently on the stats page // if (scores.isEmpty()) // { // qbean.setHistogramBars(new HistogramBarBean[0]); // qbean.setNumResponses(0); // qbean.setPercentCorrect(rb.getString("no_responses")); // return; // } PublishedAssessmentService pubService = new PublishedAssessmentService(); PublishedItemService pubItemService = new PublishedItemService(); //build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService.preparePublishedItemHash(pub); HashMap publishedItemTextHash = pubService.preparePublishedItemTextHash(pub); HashMap publishedAnswerHash = pubService.preparePublishedAnswerHash(pub); // re-attach session and load all lazy loaded parent/child stuff // Set<Long> publishedAnswerHashKeySet = publishedAnswerHash.keySet(); // // for(Long key : publishedAnswerHashKeySet) { // AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(key); // // if (! Hibernate.isInitialized(answer.getChildAnswerSet())) { // pubItemService.eagerFetchAnswer(answer); // } // } //int numAnswers = 0; ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(qbean.getItemId()); List text = item.getItemTextArraySorted(); List answers = null; //keys number of correct answers required by sub-question (ItemText) HashMap emiRequiredCorrectAnswersCount = null; if (qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) { //EMI emiRequiredCorrectAnswersCount = new HashMap(); answers = new ArrayList(); for (int i=0; i<text.size(); i++) { ItemTextIfc iText = (ItemTextIfc) publishedItemTextHash.get(((ItemTextIfc) text.toArray()[i]).getId()); if (iText.isEmiQuestionItemText()) { boolean requireAllCorrectAnswers = true; int numCorrectAnswersRequired = 0; if (iText.getRequiredOptionsCount()!=null && iText.getRequiredOptionsCount().intValue()>0) { requireAllCorrectAnswers = false; numCorrectAnswersRequired = iText.getRequiredOptionsCount().intValue(); } if (iText.getAnswerArraySorted() == null) continue; Iterator ansIter = iText.getAnswerArraySorted().iterator(); while (ansIter.hasNext()) { AnswerIfc answer = (AnswerIfc)ansIter.next(); answers.add(answer); if (requireAllCorrectAnswers && answer.getIsCorrect()) { numCorrectAnswersRequired++; } } emiRequiredCorrectAnswersCount.put(iText.getId(), Integer.valueOf(numCorrectAnswersRequired)); } } } else if (!qbean.getQuestionType().equals(TypeIfc.MATCHING.toString())) // matching { ItemTextIfc firstText = (ItemTextIfc) publishedItemTextHash.get(((ItemTextIfc) text.toArray()[0]).getId()); answers = firstText.getAnswerArraySorted(); } if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())) // mcsc getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())) // mcmc getFIBMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())) getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())) getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())) // tf getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if ((qbean.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()))||(qbean.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())) ) getFIBMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); //else if (qbean.getQuestionType().equals("11")) // getFINMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MATCHING.toString())) getMatchingScores(publishedItemTextHash, publishedAnswerHash, scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) getEMIScores(publishedItemHash, publishedAnswerHash, emiRequiredCorrectAnswersCount, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MATRIX_CHOICES_SURVEY.toString())) // matrix survey question getMatrixSurveyScores(publishedItemTextHash, publishedAnswerHash, scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())) // CALCULATED_QUESTION getCalculatedQuestionScores(scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.IMAGEMAP_QUESTION.toString())) // IMAGEMAP_QUESTION getImageMapQuestionScores(publishedItemTextHash, publishedAnswerHash, (ArrayList) scores, qbean, (ArrayList) text); } /** * calculates statistics for EMI questions */ private void getEMIScores(HashMap publishedItemHash, HashMap publishedAnswerHash, HashMap emiRequiredCorrectAnswersCount, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); // Answers keyed by answer-id HashMap answersById = new HashMap(); //keys the number of student responses selecting a particular answer //by the Answer ID HashMap results = new HashMap(); //keys Answer-IDs by subQuestion/ItemTextSequence-answerSequence (concatenated) HashMap sequenceMap = new HashMap(); //list of answers for each sub-question/ItemText ArrayList subQuestionAnswers = null; //Map which keys above lists by the sub-question/ItemText sequence HashMap subQuestionAnswerMap = new HashMap(); //Create a Map where each Sub-Question's Answers-ArrayList //is keyed by sub-question and answer sequence Iterator iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); answersById.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getItemText().getSequence() + "-" + answer.getSequence(), answer.getId()); Long subQuestionSequence = answer.getItemText().getSequence(); Object subSeqAns = subQuestionAnswerMap.get(subQuestionSequence); if (subSeqAns == null) { subQuestionAnswers = new ArrayList(); subQuestionAnswerMap.put(subQuestionSequence, subQuestionAnswers); } else { subQuestionAnswers = (ArrayList) subSeqAns; } subQuestionAnswers.add(answer); } //Iterate through the student answers (ItemGradingData) iter = scores.iterator(); //Create a map that keys all the responses/answers (ItemGradingData) //for this question from a specific student (assessment) //by the id of that assessment (AssessmentGradingData) HashMap responsesPerStudentPerQuestionMap = new HashMap(); //and do the same for seperate sub-questions HashMap responsesPerStudentPerSubQuestionMap = new HashMap(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); //Get the published answer that corresponds to the student's reponse AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); //This should always be the case as only valid responses //from the list of available options are allowed if (answer != null) { // log.info("Gopal: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter for the number of responses that select this published answer try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); } //If this published answer has not been selected before if (num == null) num = Integer.valueOf(0); //Now create a map that keys all the responses (ItemGradingData) //for this question from a specific student (or assessment) //by the id of that assessment (AssessmentGradingData) ArrayList studentResponseList = (ArrayList) responsesPerStudentPerQuestionMap .get(data.getAssessmentGradingId()); if (studentResponseList == null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); responsesPerStudentPerQuestionMap.put(data.getAssessmentGradingId(), studentResponseList); //Do the same for the sub-questions String key = data.getAssessmentGradingId() + "-" + answer.getItemText().getId(); ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap .get(key); if (studentResponseListForSubQuestion == null) { studentResponseListForSubQuestion = new ArrayList(); } studentResponseListForSubQuestion.add(data); responsesPerStudentPerSubQuestionMap.put(key, studentResponseListForSubQuestion); results.put(answer.getId(), Integer.valueOf( num.intValue() + 1)); } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; //List of "ItemText.sequence-Answer.sequence" List<String> sequenceList = new ArrayList<String>(); iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getItemText().getSequence() + "-" + answer.getSequence()); } // sort the sequence Collections.sort(sequenceList, new Comparator<String>(){ public int compare(String o1, String o2) { Integer a1 = Integer.valueOf(o1.substring(0, o1.indexOf("-"))); Integer a2 = Integer.valueOf(o2.substring(0, o1.indexOf("-"))); int val = a1.compareTo(a2); if(val != 0){ return val; } a1 = Integer.valueOf(o1.substring(o1.indexOf("-")+1)); a2 = Integer.valueOf(o2.substring(o1.indexOf("-")+1)); return a1.compareTo(a2); } }); // iter = results.keySet().iterator(); iter = sequenceList.iterator(); int i = 0; int responses = 0; int correctresponses = 0; while (iter.hasNext()) { String sequenceId = (String) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) answersById.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); if (answer != null) { bars[i].setSubQuestionSequence(answer.getItemText().getSequence()); if (answer.getItem().getIsAnswerOptionsSimple()) { bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel() + " " + answer.getText()); } else { //rich text or attachment options bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel()); } if (answer.getLabel().equals("A")) { String title = rb.getString("item") + " " + answer.getItemText().getSequence(); String text = answer.getItemText().getText(); if (text != null && !text.equals(null)) { title += " : " + text; bars[i].setTitle(title); } } bars[i].setIsCorrect(answer.getIsCorrect()); } bars[i].setNumStudentsText(num + " " + rb.getString("responses")); bars[i].setNumStudents(num); i++; }// end while responses = responsesPerStudentPerQuestionMap.size(); //Determine the number of students with all correct responses for the whole question for (Iterator it = responsesPerStudentPerQuestionMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // iterate through the results for one student // for this question (qbean) while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData) listiter.next(); // only answered choices are created in the // ItemGradingData_T, so we need to check // if # of checkboxes the student checked is == the number // of correct answers // otherwise if a student only checked one of the multiple // correct answers, // it would count as a correct response try { int corranswers = 0; Iterator answeriter = answers.iterator(); while (answeriter.hasNext()) { AnswerIfc answerchoice = (AnswerIfc) answeriter .next(); if (answerchoice.getIsCorrect().booleanValue()) { corranswers++; } } if (resultsForOneStudent.size() != corranswers) { hasIncorrect = true; break; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "error calculating emi question."); } // now check each answer AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // end for - number of students with all correct responses for the whole question // NEW int[] heights = calColumnHeight(numarray, responses); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch(NullPointerException npe) { log.warn("null column height " + npe); } } qbean.setHistogramBars(bars); qbean.setNumResponses(responses); if (responses > 0) qbean.setPercentCorrect(Integer.toString((int) (((double) correctresponses / (double) responses) * 100))); HashMap numStudentsWithAllCorrectPerSubQuestion = new HashMap(); HashMap studentsWithAllCorrectPerSubQuestion = new HashMap(); HashMap studentsRespondedPerSubQuestion = new HashMap(); Iterator studentSubquestionResponseKeyIter = responsesPerStudentPerSubQuestionMap.keySet().iterator(); while (studentSubquestionResponseKeyIter.hasNext()) { String key = (String)studentSubquestionResponseKeyIter.next(); ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap .get(key); if (studentResponseListForSubQuestion != null && !studentResponseListForSubQuestion.isEmpty()) { ItemGradingData response1 = (ItemGradingData)studentResponseListForSubQuestion.get(0); Long subQuestionId = ((AnswerIfc)publishedAnswerHash.get(response1.getPublishedAnswerId())).getItemText().getId(); Set studentsResponded = (Set)studentsRespondedPerSubQuestion.get(subQuestionId); if (studentsResponded == null) studentsResponded = new TreeSet(); studentsResponded.add(response1.getAgentId()); studentsRespondedPerSubQuestion.put(subQuestionId, studentsResponded); boolean hasIncorrect = false; //numCorrectSubQuestionAnswers = (Integer) correctAnswersPerSubQuestion.get(subQuestionId); Integer numCorrectSubQuestionAnswers = (Integer) emiRequiredCorrectAnswersCount.get(subQuestionId); if (studentResponseListForSubQuestion.size() < numCorrectSubQuestionAnswers.intValue()) { hasIncorrect = true; continue; } //now check each answer Iterator studentResponseIter = studentResponseListForSubQuestion.iterator(); while (studentResponseIter.hasNext()) { ItemGradingData response = (ItemGradingData)studentResponseIter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(response .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } if (hasIncorrect) continue; Integer numWithAllCorrect = (Integer)numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (numWithAllCorrect == null) { numWithAllCorrect = Integer.valueOf(0); } numStudentsWithAllCorrectPerSubQuestion.put(subQuestionId, Integer.valueOf(numWithAllCorrect.intValue() + 1)); Set studentsWithAllCorrect = (Set)studentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (studentsWithAllCorrect == null) studentsWithAllCorrect = new TreeSet(); studentsWithAllCorrect.add(response1.getAgentId()); studentsWithAllCorrectPerSubQuestion.put(subQuestionId, studentsWithAllCorrect); } } //Map ItemText sequences to Ids HashMap itemTextSequenceIdMap = new HashMap(); Iterator answersIter = answers.iterator(); while (answersIter.hasNext()) { AnswerIfc answer = (AnswerIfc)answersIter.next(); itemTextSequenceIdMap.put(answer.getItemText().getSequence(), answer.getItemText().getId()); } //Now select the the bars for each sub-questions Set subQuestionKeySet = subQuestionAnswerMap.keySet(); ArrayList subQuestionKeyList = new ArrayList(); subQuestionKeyList.addAll(subQuestionKeySet); Collections.sort(subQuestionKeyList); Iterator subQuestionIter = subQuestionKeyList.iterator(); ArrayList subQuestionInfo = new ArrayList(); //List of sub-question HistogramQuestionScoresBeans - for EMI sub-questions // Iterate through the assessment questions (items) while (subQuestionIter.hasNext()) { Long subQuestionSequence = (Long)subQuestionIter.next(); //While qbean is the HistogramQuestionScoresBean for the entire question //questionScores are the HistogramQuestionScoresBeans for each sub-question HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean(); questionScores.setSubQuestionSequence(subQuestionSequence); // Determine the number of bars (possible answers) for this sub-question int numBars = 0; for (int j=0; j<bars.length; j++) { if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) { numBars++; } } //Now create an array of that size //and populate it with the bars for this sub-question HistogramBarBean[] subQuestionBars = new HistogramBarBean[numBars]; int subBar = 0; for (int j=0; j<bars.length; j++) { if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) { subQuestionBars[subBar++]=bars[j]; } } questionScores.setShowIndividualAnswersInDetailedStatistics(true); questionScores.setHistogramBars(subQuestionBars); questionScores.setNumberOfParts(qbean.getNumberOfParts()); //if this part is a randompart , then set randompart = true questionScores.setRandomType(qbean.getRandomType()); questionScores.setPartNumber(qbean.getPartNumber()); questionScores.setQuestionNumber(qbean.getQuestionNumber()+"-"+subQuestionSequence); questionScores.setQuestionText(qbean.getQuestionText()); questionScores.setQuestionType(qbean.getQuestionType()); questionScores.setN(qbean.getN()); questionScores.setItemId(qbean.getItemId()); //This boild down to the number of AssessmentGradingData //So should be the same for whole and sub questions questionScores.setNumResponses(qbean.getNumResponses()); Long subQuestionId = (Long)itemTextSequenceIdMap.get(subQuestionSequence); if (questionScores.getNumResponses() > 0) { Integer numWithAllCorrect = (Integer)numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (numWithAllCorrect != null) correctresponses = numWithAllCorrect.intValue(); questionScores.setPercentCorrect(Integer.toString((int) (((double) correctresponses / (double) responses) * 100))); } Set studentsWithAllCorrect = (Set)studentsWithAllCorrectPerSubQuestion.get(subQuestionId); questionScores.setStudentsWithAllCorrect(studentsWithAllCorrect); Set studentsResponded = (Set)studentsRespondedPerSubQuestion.get(subQuestionId); questionScores.setStudentsResponded(studentsResponded); subQuestionAnswers = (ArrayList) subQuestionAnswerMap.get(subQuestionSequence); Iterator answerIter = subQuestionAnswers.iterator(); Double totalScore = new Double(0); while (answerIter.hasNext()) { AnswerIfc subQuestionAnswer = (AnswerIfc) answerIter.next(); totalScore += (subQuestionAnswer==null||subQuestionAnswer.getScore()==null?0.0:subQuestionAnswer.getScore()); } questionScores.setTotalScore(totalScore.toString()); HistogramScoresBean histogramScores = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); Iterator keys = responsesPerStudentPerSubQuestionMap.keySet().iterator(); int numSubmissions = 0; while (keys.hasNext()) { String assessmentAndSubquestionId = (String)keys.next(); if (assessmentAndSubquestionId.endsWith("-"+subQuestionId)) numSubmissions++; } int percent27 = numSubmissions*27/100; // rounded down if (percent27 == 0) percent27 = 1; studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect(); studentsResponded = questionScores.getStudentsResponded(); if (studentsWithAllCorrect == null || studentsResponded == null || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) { questionScores.setPercentCorrectFromUpperQuartileStudents("0"); questionScores.setPercentCorrectFromLowerQuartileStudents("0"); questionScores.setDiscrimination("0.0"); } else { int numStudentsWithAllCorrectFromUpperQuartile = 0; int numStudentsWithAllCorrectFromLowerQuartile = 0; Iterator studentsIter = studentsWithAllCorrect.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (histogramScores.isUpperQuartileStudent(agentId)) { numStudentsWithAllCorrectFromUpperQuartile++; } if (histogramScores.isLowerQuartileStudent(agentId)) { numStudentsWithAllCorrectFromLowerQuartile++; } } int numStudentsRespondedFromUpperQuartile = 0; int numStudentsRespondedFromLowerQuartile = 0; studentsIter = studentsResponded.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (histogramScores.isUpperQuartileStudent(agentId)) { numStudentsRespondedFromUpperQuartile++; } if (histogramScores.isLowerQuartileStudent(agentId)) { numStudentsRespondedFromLowerQuartile++; } } double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile / (double) percent27) * 100d; double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile / (double) percent27) * 100d; questionScores.setPercentCorrectFromUpperQuartileStudents( Integer.toString((int) percentCorrectFromUpperQuartileStudents)); questionScores.setPercentCorrectFromLowerQuartileStudents( Integer.toString((int) percentCorrectFromLowerQuartileStudents)); double numResponses = (double)questionScores.getNumResponses(); double discrimination = ((double)numStudentsWithAllCorrectFromUpperQuartile - (double)numStudentsWithAllCorrectFromLowerQuartile)/(double)percent27 ; // round to 2 decimals if (discrimination > 999999 || discrimination < -999999) { questionScores.setDiscrimination("NaN"); } else { discrimination = ((int) (discrimination*100.00)) / 100.00; questionScores.setDiscrimination(Double.toString(discrimination)); } } subQuestionInfo.add(questionScores); } // end-while - items qbean.setInfo(subQuestionInfo); } private void getFIBMCMCScores(HashMap publishedItemHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); HashMap texts = new HashMap(); Iterator iter = answers.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap = new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getSequence(), answer.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { // log.info("Rachel: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); } if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList) numStudentRespondedMap .get(data.getAssessmentGradingId()); if (studentResponseList == null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); // we found a response, and got the existing num , now update // one if ((qbean.getQuestionType().equals("8")) || (qbean.getQuestionType().equals("11"))) { // for fib we only count the number of correct responses Double autoscore = data.getAutoScore(); if (!(Double.valueOf(0)).equals(autoscore)) { results.put(answer.getId(), Integer.valueOf( num.intValue() + 1)); } } else { // for mc, we count the number of all responses results .put(answer.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getSequence()); } Collections.sort(sequenceList); // iter = results.keySet().iterator(); iter = sequenceList.iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) texts.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); if (answer != null) bars[i].setLabel(answer.getText()); // this doens't not apply to fib , do not show checkmarks for FIB if (!(qbean.getQuestionType().equals("8")) && !(qbean.getQuestionType().equals("11")) && answer != null) { bars[i].setIsCorrect(answer.getIsCorrect()); } if ((num > 1) || (num == 0)) { bars[i].setNumStudentsText(num + " " + rb.getString("responses")); } else { bars[i] .setNumStudentsText(num + " " + rb.getString("response")); } bars[i].setNumStudents(num); i++; } for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // iterate through the results for one student // for this question (qbean) while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData) listiter.next(); if ((qbean.getQuestionType().equals("8")) || (qbean.getQuestionType().equals("11"))) { // TODO: we are checking to see if the score is > 0, this // will not work if the question is worth 0 points. // will need to verify each answer individually. Double autoscore = item.getAutoScore(); if ((Double.valueOf(0)).equals(autoscore)) { hasIncorrect = true; break; } } else if (qbean.getQuestionType().equals("2")) { // mcmc // only answered choices are created in the // ItemGradingData_T, so we need to check // if # of checkboxes the student checked is == the number // of correct answers // otherwise if a student only checked one of the multiple // correct answers, // it would count as a correct response try { List itemTextArray = ((ItemDataIfc) publishedItemHash .get(item.getPublishedItemId())) .getItemTextArraySorted(); List answerArray = ((ItemTextIfc) itemTextArray .get(0)).getAnswerArraySorted(); int corranswers = 0; Iterator answeriter = answerArray.iterator(); while (answeriter.hasNext()) { AnswerIfc answerchoice = (AnswerIfc) answeriter .next(); if (answerchoice.getIsCorrect().booleanValue()) { corranswers++; } } if (resultsForOneStudent.size() != corranswers) { hasIncorrect = true; break; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "error calculating mcmc question."); } // now check each answer in MCMC AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch(NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean .setPercentCorrect(Integer .toString((int) (((double) correctresponses / (double) qbean.getNumResponses()) * 100))); } /* * private void getFINMCMCScores(HashMap publishedItemHash, HashMap * publishedAnswerHash, ArrayList scores, HistogramQuestionScoresBean qbean, * ArrayList answers) { HashMap texts = new HashMap(); Iterator iter = * answers.iterator(); HashMap results = new HashMap(); HashMap * numStudentRespondedMap= new HashMap(); while (iter.hasNext()) { AnswerIfc * answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); * results.put(answer.getId(), Integer.valueOf(0)); } iter = scores.iterator(); * while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) * iter.next(); AnswerIfc answer = (AnswerIfc) * publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer != null) { * //log.info("Rachel: looking for " + answer.getId()); // found a response * Integer num = null; // num is a counter try { // we found a response, now * get existing count from the hashmap num = (Integer) * results.get(answer.getId()); * * } catch (Exception e) { log.warn("No results for " + answer.getId()); } * if (num == null) num = Integer.valueOf(0); * * ArrayList studentResponseList = * (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if * (studentResponseList==null) { studentResponseList = new ArrayList(); } * studentResponseList.add(data); * numStudentRespondedMap.put(data.getAssessmentGradingId(), * studentResponseList); // we found a response, and got the existing num , * now update one if (qbean.getQuestionType().equals("11")) { // for fib we * only count the number of correct responses Double autoscore = * data.getAutoScore(); if (!(new Double(0)).equals(autoscore)) { * results.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); } } else { // * for mc, we count the number of all responses results.put(answer.getId(), * Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new * HistogramBarBean[results.keySet().size()]; int[] numarray = new * int[results.keySet().size()]; iter = results.keySet().iterator(); int i = * 0; int responses = 0; int correctresponses = 0; while (iter.hasNext()) { * Long answerId = (Long) iter.next(); AnswerIfc answer = (AnswerIfc) * texts.get(answerId); int num = ((Integer) * results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new * HistogramBarBean(); if(answer != null) * bars[i].setLabel(answer.getText()); * // this doens't not apply to fib , do not show checkmarks for FIB if * (!qbean.getQuestionType().equals("11") && answer != null) { * bars[i].setIsCorrect(answer.getIsCorrect()); } * * * if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " Responses"); } * else { bars[i].setNumStudentsText(num + " Response"); * } bars[i].setNumStudents(num); i++; } * * * responses = numStudentRespondedMap.size(); Iterator mapiter = * numStudentRespondedMap.keySet().iterator(); while (mapiter.hasNext()) { * Long assessmentGradingId= (Long)mapiter.next(); ArrayList * resultsForOneStudent = * (ArrayList)numStudentRespondedMap.get(assessmentGradingId); boolean * hasIncorrect = false; Iterator listiter = * resultsForOneStudent.iterator(); while (listiter.hasNext()) { * ItemGradingData item = (ItemGradingData)listiter.next(); if * (qbean.getQuestionType().equals("11")) { Double autoscore = * item.getAutoScore(); if (!(new Double(0)).equals(autoscore)) { * hasIncorrect = true; break; } } else if * (qbean.getQuestionType().equals("2")) { * // only answered choices are created in the ItemGradingData_T, so we * need to check // if # of checkboxes the student checked is == the number * of correct answers // otherwise if a student only checked one of the * multiple correct answers, // it would count as a correct response * * try { ArrayList itemTextArray = * ((ItemDataIfc)publishedItemHash.get(item.getPublishedItemId())).getItemTextArraySorted(); * ArrayList answerArray = * ((ItemTextIfc)itemTextArray.get(0)).getAnswerArraySorted(); * * int corranswers = 0; Iterator answeriter = answerArray.iterator(); while * (answeriter.hasNext()){ AnswerIfc answerchoice = (AnswerIfc) * answeriter.next(); if (answerchoice.getIsCorrect().booleanValue()){ * corranswers++; } } if (resultsForOneStudent.size() != corranswers){ * hasIncorrect = true; break; } } catch (Exception e) { * e.printStackTrace(); throw new RuntimeException("error calculating mcmc * question."); } * // now check each answer in MCMC * * AnswerIfc answer = (AnswerIfc) * publishedAnswerHash.get(item.getPublishedAnswerId()); if ( answer != null && * (answer.getIsCorrect() == null || * (!answer.getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } } * if (!hasIncorrect) { correctresponses = correctresponses + 1; } } //NEW * int[] heights = calColumnHeight(numarray,responses); // int[] heights = * calColumnHeight(numarray); for (i=0; i<bars.length; i++) * bars[i].setColumnHeight(Integer.toString(heights[i])); * qbean.setHistogramBars(bars); qbean.setNumResponses(responses); if * (responses > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) * correctresponses/(double) responses) * 100))); } */ private void getTFMCScores(HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); HashMap texts = new HashMap(); Iterator iter = answers.iterator(); HashMap results = new HashMap(); HashMap sequenceMap = new HashMap(); // create the lookup maps while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getSequence(), answer.getId()); } // find the number of responses (ItemGradingData) for each answer iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { // log.info("Rachel: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); e.printStackTrace(); } if (num == null) num = Integer.valueOf(0); // we found a response, and got the existing num , now update // one // check here for the other bug about non-autograded items // having 1 even with no responses results.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); // this should work because for tf/mc(single) // questions, there should be at most // one submitted answer per student/assessment if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { qbean.addStudentWithAllCorrect(data.getAgentId()); } qbean.addStudentResponded(data.getAgentId()); } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); // get an arraylist of answer sequences iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getSequence()); } // sort the sequences Collections.sort(sequenceList); iter = sequenceList.iterator(); // iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; // find answers sorted by sequence while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) texts.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); // set i to be the sequence, so that the answer choices will be in // the right order on Statistics page , see Bug SAM-440 i = answer.getSequence().intValue() - 1; numarray[i] = num; bars[i] = new HistogramBarBean(); if (qbean.getQuestionType().equals("4")) { // true-false String origText = answer.getText(); String text = ""; if ("true".equals(origText)) { text = rb.getString("true_msg"); } else { text = rb.getString("false_msg"); } bars[i].setLabel(text); } else { bars[i].setLabel(answer.getText()); } bars[i].setIsCorrect(answer.getIsCorrect()); if ((num > 1) || (num == 0)) { bars[i].setNumStudentsText(num + " " + rb.getString("responses")); } else { bars[i] .setNumStudentsText(num + " " + rb.getString("response")); } bars[i].setNumStudents(num); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { correctresponses += num; } // i++; } // NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean .setPercentCorrect(Integer .toString((int) (((double) correctresponses / (double) qbean.getNumResponses()) * 100))); } private void getCalculatedQuestionScores(List<ItemGradingData> scores, HistogramQuestionScoresBean qbean, List labels) { final String CORRECT = "Correct"; final String INCORRECT = "Incorrect"; final int COLUMN_MAX_HEIGHT = 600; ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); // count incorrect and correct to support column height calculation Map<String, Integer> results = new HashMap<String, Integer>(); results.put(CORRECT, Integer.valueOf(0)); results.put(INCORRECT, Integer.valueOf(0)); for (ItemGradingData score : scores) { if (score.getAutoScore() != null && score.getAutoScore() > 0) { Integer value = results.get(CORRECT); results.put(CORRECT, ++value); } else { Integer value = results.get(INCORRECT); results.put(INCORRECT, ++value); } } // build the histogram bar for correct/incorrect answers List<HistogramBarBean> barList = new ArrayList<HistogramBarBean>(); for (Map.Entry<String, Integer> entry : results.entrySet()) { HistogramBarBean bar = new HistogramBarBean(); bar.setLabel(entry.getKey()); bar.setNumStudents(entry.getValue()); if (entry.getValue() > 1) { bar.setNumStudentsText(entry.getValue() + " " + rb.getString("correct_responses")); } else { bar.setNumStudentsText(entry.getValue() + " " + rc.getString("correct_response")); } bar.setNumStudentsText(entry.getValue() + " " + entry.getKey()); bar.setIsCorrect(entry.getKey().equals(CORRECT)); int height = 0; if (scores.size() > 0) { height = COLUMN_MAX_HEIGHT * entry.getValue() / scores.size(); } bar.setColumnHeight(Integer.toString(height)); barList.add(bar); } HistogramBarBean[] bars = new HistogramBarBean[barList.size()]; bars = barList.toArray(bars); qbean.setHistogramBars(bars); // store any assessment grading ID's that are incorrect. // this will allow us to calculate % Students All correct by giving // us a count of assessmnets that had an incorrect answer Set<Long> assessmentQuestionIncorrect = new HashSet<Long>(); for (ItemGradingData score : scores) { if (score.getAutoScore() == null || score.getAutoScore() == 0) { assessmentQuestionIncorrect.add(score.getAssessmentGradingId()); } } if (qbean.getNumResponses() > 0) { int correct = qbean.getNumResponses() - assessmentQuestionIncorrect.size(); int total = qbean.getNumResponses(); double percentCorrect = ((double) correct / (double) total) * 100; String percentCorrectStr = Integer.toString((int)percentCorrect); qbean.setPercentCorrect(percentCorrectStr); } } private void getImageMapQuestionScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, ArrayList scores, HistogramQuestionScoresBean qbean, ArrayList labels) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); HashMap texts = new HashMap(); Iterator iter = labels.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap= new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); results.put(label.getId(), Integer.valueOf(0)); sequenceMap.put(label.getSequence(), label.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); ItemTextIfc text = (ItemTextIfc) publishedItemTextHash.get(data.getPublishedItemTextId()); if (text != null) { Integer num = (Integer) results.get(text.getId()); if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); //if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) if (data.getIsCorrect() != null && data.getIsCorrect().booleanValue()) // only store correct responses in the results { results.put(text.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = labels.iterator(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); sequenceList.add(label.getSequence()); } Collections.sort(sequenceList); iter = sequenceList.iterator(); //iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long textId = (Long) sequenceMap.get(sequenceId); ItemTextIfc text = (ItemTextIfc) texts.get(textId); int num = ((Integer) results.get(textId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); bars[i].setLabel(text.getText()); bars[i].setNumStudents(num); if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " " +rb.getString("correct_responses")); } else { bars[i].setNumStudentsText(num + " " +rc.getString("correct_response")); } i++; } // now calculate correctresponses // correctresponses = # of students who got all answers correct, for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // numStudentRespondedMap only stores correct answers, so now we need to // check to see if # of rows in itemgradingdata_t == labels.size() // otherwise if a student only answered one correct answer and // skipped the rest, it would count as a correct response while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData)listiter.next(); if (resultsForOneStudent.size()!= labels.size()){ hasIncorrect = true; break; } // now check each answer in Matching //AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item.getPublishedAnswerId()); if (item.getIsCorrect() == null || (!item.getIsCorrect().booleanValue())) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; // gopalrc - Nov 2007 qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // gopalrc - Dec 2007 qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } //NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i=0; i<bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) correctresponses/(double) qbean.getNumResponses()) * 100))); } private void getMatchingScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List labels) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); HashMap texts = new HashMap(); Iterator iter = labels.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap= new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); results.put(label.getId(), Integer.valueOf(0)); sequenceMap.put(label.getSequence(), label.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); ItemTextIfc text = (ItemTextIfc) publishedItemTextHash.get(data.getPublishedItemTextId()); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); // if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) if (answer != null) { Integer num = (Integer) results.get(text.getId()); if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) // only store correct responses in the results { results.put(text.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = labels.iterator(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); sequenceList.add(label.getSequence()); } Collections.sort(sequenceList); iter = sequenceList.iterator(); //iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long textId = (Long) sequenceMap.get(sequenceId); ItemTextIfc text = (ItemTextIfc) texts.get(textId); int num = ((Integer) results.get(textId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); bars[i].setLabel(text.getText()); bars[i].setNumStudents(num); if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " " +rb.getString("correct_responses")); } else { bars[i].setNumStudentsText(num + " " +rc.getString("correct_response")); } i++; } // now calculate correctresponses // correctresponses = # of students who got all answers correct, for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // numStudentRespondedMap only stores correct answers, so now we need to // check to see if # of rows in itemgradingdata_t == labels.size() // otherwise if a student only answered one correct answer and // skipped the rest, it would count as a correct response while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData)listiter.next(); if (resultsForOneStudent.size()!= labels.size()){ hasIncorrect = true; break; } // now check each answer in Matching AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item.getPublishedAnswerId()); if (answer.getIsCorrect() == null || (!answer.getIsCorrect().booleanValue())) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } //NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i=0; i<bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) correctresponses/(double) qbean.getNumResponses()) * 100))); } private void getMatrixSurveyScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List labels) { HashMap texts = new HashMap(); HashMap rows = new HashMap(); HashMap answers = new HashMap(); HashMap numStudentRespondedMap = new HashMap(); Iterator iter = labels.iterator(); // create labels(rows) and HashMap , rows has the total count of response for that row while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); rows.put(label.getId(), Integer.valueOf(0)); // sequenceMap.put(label.getSequence(), label.getId()); } // log.info("kim debug: row size and texts size " + rows.keySet().size()+ " " + texts.keySet().size()); // result only contains the row information, I should have another HashMap to store the Answer results // find the number of responses (ItemGradingData) for each answer iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { Integer num = null; // num is a counter try { // we found a response, now get existing count from the hashmap // num = (Integer) results.get(answer.getId()); num = (Integer) answers.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); log.error(e.getMessage()); } if (num == null) num = Integer.valueOf(0); answers.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); Long id = ((ItemTextIfc)answer.getItemText()).getId(); Integer rCount = null; try { rCount = (Integer)rows.get(id); } catch (Exception e) { log.warn("No results for " + id); log.error(e.getMessage()); } if(rCount != null) rows.put(id, Integer.valueOf(rCount.intValue()+1)); } ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); qbean.addStudentResponded(data.getAgentId()); } //create the arraylist for answer text ArrayList answerTextList = new ArrayList<String>(); iter = publishedAnswerHash.keySet().iterator(); boolean isIn = false; while(iter.hasNext()){ Long id = (Long)iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(id); if (!qbean.getItemId().equals(answer.getItem().getItemId())) { continue; } isIn = false; //log.info("kim debug: publishedAnswerHash: key value " + id + answer.getText()); for(int i=0; i< answerTextList.size(); i++){ if((((String)answer.getText()).trim()).equals(((String)answerTextList.get(i)).trim())){ isIn = true; break; } } if(!isIn){ String ansStr = answer.getText().trim(); answerTextList.add(ansStr); } } //create the HistogramBarBean ArrayList<HistogramBarBean> histogramBarList = new ArrayList<HistogramBarBean>(); iter = texts.keySet().iterator(); while (iter.hasNext()){ Long id = (Long)iter.next(); HistogramBarBean gramBar = new HistogramBarBean(); ItemTextIfc ifc = (ItemTextIfc)texts.get(id); Integer totalCount = (Integer)rows.get(id); //log.info("kim debug: total count: " + totalCount.intValue()); //log.info("kim debug: row.next()" + ifc.getText()); gramBar.setLabel(ifc.getText()); //add each small beans ArrayList<ItemBarBean> itemBars = new ArrayList<ItemBarBean>(); for(int i=0; i< answerTextList.size(); i++){ ItemBarBean barBean = new ItemBarBean(); int count = 0; //get the count of checked //1. first get the answerId for ItemText+AnswerText combination Iterator iter1 = publishedAnswerHash.keySet().iterator(); while(iter1.hasNext()){ Long id1 = (Long)iter1.next(); AnswerIfc answer1 = (AnswerIfc)publishedAnswerHash.get(id1); //log.info("kim debug:answer1.getText() + ifc.getText()" + //answer1.getText() + answer1.getItemText().getText() + ifc.getText() + answer1.getId()); // bjones86 - SAM-2232 - null checks if( answer1 == null ) { continue; } ItemTextIfc answer1ItemText = answer1.getItemText(); if( answer1ItemText == null ) { continue; } String answer1Text = answer1.getText(); String answer1ItemTextText = answer1ItemText.getText(); if( answer1Text == null || answer1ItemTextText == null ) { continue; } String answerText = (String) answerTextList.get( i ); String ifcText = ifc.getText(); if(answer1Text.equals(answerText) && answer1ItemTextText.equals(ifcText)) { //2. then get the count from HashMap if(answers.containsKey(answer1.getId())) { count =((Integer) answers.get(answer1.getId())).intValue(); //log.info("kim debug: count " + count); break; } } } if (count > 1) barBean.setNumStudentsText(count + " responses"); else barBean.setNumStudentsText(count + " response"); //2. get the answer text barBean.setItemText((String)answerTextList.get(i)); //log.info("kim debug: getItemText " + barBean.getItemText()); //3. set the columnHeight int height= 0; if (totalCount.intValue() != 0) height = 300 * count/totalCount.intValue(); barBean.setColumnHeight(Integer.toString(height)); itemBars.add(barBean); } //log.info("kim debug: itemBars size: " +itemBars.size()); gramBar.setItemBars(itemBars); histogramBarList.add(gramBar); } //debug purpose //log.info("kim debug: histogramBarList size: " +histogramBarList.size()); qbean.setHistogramBars(histogramBarList.toArray(new HistogramBarBean[histogramBarList.size()])); qbean.setNumResponses(numStudentRespondedMap.size()); } private void doScoreStatistics(HistogramQuestionScoresBean qbean, ArrayList scores) { // here scores contain ItemGradingData Map assessmentMap = getAssessmentStatisticsMap(scores); // test to see if it gets back empty map if (assessmentMap.isEmpty()) { qbean.setNumResponses(0); } try { BeanUtils.populate(qbean, assessmentMap); // quartiles don't seem to be working, workaround qbean.setQ1( (String) assessmentMap.get("q1")); qbean.setQ2( (String) assessmentMap.get("q2")); qbean.setQ3( (String) assessmentMap.get("q3")); qbean.setQ4( (String) assessmentMap.get("q4")); //qbean.setTotalScore( (String) assessmentMap.get("maxScore")); HistogramBarBean[] bars = new HistogramBarBean[qbean.getColumnHeight().length]; // SAK-1933: if there is no response, do not show bars at all // do not check if assessmentMap is empty, because it's never empty. if (scores.size() == 0) { bars = new HistogramBarBean[0]; } else { for (int i=0; i<qbean.getColumnHeight().length; i++) { bars[i] = new HistogramBarBean(); bars[i].setColumnHeight (Integer.toString(qbean.getColumnHeight()[i])); bars[i].setNumStudents(qbean.getNumStudentCollection()[i]); if (qbean.getNumStudentCollection()[i]>1) { bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Responses"); } else { bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Response"); } // bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + // " Responses"); bars[i].setRangeInfo(qbean.getRangeCollection()[i]); bars[i].setLabel(qbean.getRangeCollection()[i]); } } qbean.setHistogramBars(bars); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } private Map getAssessmentStatisticsMap(ArrayList scoreList) { // this function is used to calculate stats for an entire assessment // or for a non-autograded question // depending on data's instanceof Iterator iter = scoreList.iterator(); ArrayList doubles = new ArrayList(); while (iter.hasNext()) { Object data = iter.next(); if (data instanceof AssessmentGradingData) { Double finalScore = ((AssessmentGradingData) data).getFinalScore(); if (finalScore == null) { finalScore = Double.valueOf("0"); } doubles.add(finalScore); } else { double autoScore = (double) 0.0; if (((ItemGradingData) data).getAutoScore() != null) autoScore = ((ItemGradingData) data).getAutoScore().doubleValue(); double overrideScore = (double) 0.0; if (((ItemGradingData) data).getOverrideScore() != null) overrideScore = ((ItemGradingData) data).getOverrideScore().doubleValue(); doubles.add(Double.valueOf(autoScore + overrideScore)); } } if (doubles.isEmpty()) doubles.add(new Double(0.0)); Object[] array = doubles.toArray(); Arrays.sort(array); double[] scores = new double[array.length]; for (int i=0; i<array.length; i++) { scores[i] = Double.valueOf(castingNum((Double)array[i],2)).doubleValue(); } HashMap statMap = new HashMap(); double min = scores[0]; double max = scores[scores.length - 1]; double total = calTotal(scores); double mean = calMean(scores, total); int interval = 0; interval = calInterval(min, max); // SAM-2409 int[] numStudents = calNumStudents(scores, min, max, interval); statMap.put("maxScore", castingNum(max,2)); statMap.put("interval", Integer.valueOf(interval)); statMap.put("numResponses", Integer.valueOf(scoreList.size())); // statMap.put("numResponses", Integer.valueOf(scores.length)); statMap.put("totalScore",castingNum(total,2)); statMap.put("mean", castingNum(mean,2)); statMap.put("median", castingNum(calMedian(scores),2)); statMap.put("mode", castingNumForMode(calMode(scores))); statMap.put("numStudentCollection", numStudents); statMap.put( "rangeCollection", calRange(scores, numStudents, min, max, interval)); statMap.put("standDev", castingNum(calStandDev(scores, mean),2)); //NEW //statMap.put("columnHeight", calColumnHeight(numStudents)); statMap.put("columnHeight", calColumnHeight(numStudents,scoreList.size())); statMap.put("arrayLength", Integer.valueOf(numStudents.length)); statMap.put( "range", castingNum(scores[0],2) + " - " + castingNum(scores[scores.length - 1],2)); statMap.put("q1", castingNum(calQuartiles(scores, 0.25),2)); statMap.put("q2", castingNum(calQuartiles(scores, 0.5),2)); statMap.put("q3", castingNum(calQuartiles(scores, 0.75),2)); statMap.put("q4", castingNum(max,2)); return statMap; } /*** What follows is Huong Nguyen's statistics code. ***/ /*** We love you Huong! --rmg ***/ /** * Calculate the total score for all students * @param scores array of scores * @return the total */ private static double calTotal(double[] scores) { double total = 0; for(int i = 0; i < scores.length; i++) { total = total + scores[i]; } return total; } /** * Calculate mean. * * @param scores array of scores * @param total the total of all scores * * @return mean */ private static double calMean(double[] scores, double total) { return total / scores.length; } /** * Calculate median. * * @param scores array of scores * * @return median */ private static double calMedian(double[] scores) { double median; if(((scores.length) % 2) == 0) { median = (scores[(scores.length / 2)] + scores[(scores.length / 2) - 1]) / 2; } else { median = scores[(scores.length - 1) / 2]; } return median; } /** * Calculate mode * * @param scores array of scores * * @return mode */ private static String calMode(double[]scores){ // double[]scores={1,2,3,4,3,6,5,5,6}; Arrays.sort(scores); String maxString=""+scores[0]; int maxCount=1; int currentCount=1; for(int i=1;i<scores.length;i++){ if(!(""+scores[i]).equals(""+scores[i-1])){ currentCount=1; if(maxCount==currentCount) maxString=maxString+", "+scores[i]; } else{ currentCount++; if(maxCount==currentCount) maxString=maxString+", "+scores[i]; if(maxCount<currentCount){ maxString=""+scores[i]; maxCount=currentCount; } } } return maxString; } /** * Calculate standard Deviation * * @param scores array of scores * @param mean the mean * @param total the total * * @return the standard deviation */ private static double calStandDev(double[] scores, double mean) { double total = 0; for(int i = 0; i < scores.length; i++) { total = total + ((scores[i] - mean) * (scores[i] - mean)); } return Math.sqrt(total / (scores.length - 1)); } /** * Calculate the interval to use for histograms. * * @param scores array of scores * @param min the minimum score * @param max the maximum score * * @return the interval */ private static int calInterval(double min, double max) // SAM-2409 { int interval; if((max - min) < 10) { interval = 1; } else { interval = (int) Math.ceil((Math.ceil(max) - Math.floor(min)) / 10); // SAM-2409 } return interval; } /** * Calculate the number for each answer. * * @param answers array of answers * * * @return array of number giving each answer. */ /* private static int[] calNum(String[] answers, String[] choices, String type) { int[] num = new int[choices.length]; for(int i = 0; i < answers.length; i++) { for(int j = 0; j < choices.length; j++) { if(type.equals("Multiple Correct Answer")) { // TODO: using Tokenizer because split() doesn't seem to work. StringTokenizer st = new StringTokenizer(answers[i], "|"); while(st.hasMoreTokens()) { String nt = st.nextToken(); if((nt.trim()).equals(choices[j].trim())) { num[j] = num[j] + 1; } } } else { if(answers[i].equals(choices[j])) { num[j] = num[j] + 1; } } } } return num; } */ /** * Calculate the number correct answer * * @param answers array of answers * @param correct the correct answer * * @return the number correct */ /* private int calCorrect(String[] answers, String correct) { int cal = 0; for(int i = 0; i < answers.length; i++) { if(answers[i].equals(correct)) { cal++; } } return cal; } */ /** * Calculate the number of students per interval for histograms. * * @param scores array of scores * @param min the minimum score * @param max the maximum score * @param interval the interval * * @return number of students per interval */ private static int[] calNumStudents( double[] scores, double min, double max, int interval) { if(min > max) { //log.info("max(" + max + ") <min(" + min + ")"); max = min; } min = Math.floor(min); // SAM-2409 max = Math.ceil(max); // SAM-2409 int[] numStudents = new int[(int) Math.ceil((max - min) / interval)]; // this handles a case where there are no num students, treats as if // a single value of 0 if(numStudents.length == 0) { numStudents = new int[1]; numStudents[0] = 0; } for(int i = 0; i < scores.length; i++) { if(scores[i] <= (min + interval)) { numStudents[0]++; } else { for(int j = 1; j < (numStudents.length); j++) { if( ((scores[i] > (min + (j * interval))) && (scores[i] <= (min + ((j + 1) * interval))))) { numStudents[j]++; break; } } } } return numStudents; } /** * Get range text for each interval * * @param answers array of ansers * * * @return array of range text strings for each interval */ /* private static String[] calRange(String[] answers, String[] choices) { String[] range = new String[choices.length]; int current = 0; // gracefully handle a condition where there are no answers if(answers.length == 0) { for(int i = 0; i < range.length; i++) { range[i] = "unknown"; } return range; } choices[0] = answers[0]; for(int a = 1; a < answers.length; a++) { if(! (answers[a].equals(choices[current]))) { current++; choices[current] = answers[a]; } } return range; } */ /** * Calculate range strings for each interval. * * @param scores array of scores * @param numStudents number of students for each interval * @param min the minimium * @param max the maximum * @param interval the number of intervals * * @return array of range strings for each interval. */ private static String[] calRange( double[] scores, int[] numStudents, double min, double max, int interval) { String[] ranges = new String[numStudents.length]; if(Double.compare(max, min) == 0){ String num = castingNum(min,2); ranges[0] = num + " - " + num; } else { ranges[0] = (int) min + " - " + (int) (min + interval); int i = 1; while(i < ranges.length) { if((((i + 1) * interval) + min) < max) { ranges[i] = ">" + (int) ((i * interval) + min) + " - " + (int) (((i + 1) * interval) + min); } else { ranges[i] = ">" + (int) ((i * interval) + min) + " - " + castingNum(max,2); } i++; } } return ranges; } /** * Calculate the height of each histogram column. * * @param numStudents the number of students for each column * * @return array of column heights */ /* private static int[] calColumnHeightold(int[] numStudents) { int length = numStudents.length; int[] temp = new int[length]; int[] height = new int[length]; int i = 0; while(i < length) { temp[i] = numStudents[i]; i++; } Arrays.sort(temp); int num = 1; if((temp.length > 0) && (temp[temp.length - 1] > 0)) { num = (int) (300 / temp[temp.length - 1]); int j = 0; while(j < length) { height[j] = num * numStudents[j]; j++; } } return height; } */ private static int[] calColumnHeight(int[] numStudents, int totalResponse) { int[] height = new int[numStudents.length]; int index=0; while(index <numStudents.length){ if(totalResponse>0) height[index] = (int)((100*numStudents[index])/totalResponse); else height[index]=0; index++; } return height; } /** * Calculate quartiles. * * @param scores score array * @param r the quartile rank * * @return the quartile */ private static double calQuartiles(double[] scores, double r) { int k; double f; k = (int) (Math.floor((r * (scores.length - 1)) + 1)); f = (r * (scores.length - 1)) - Math.floor(r * (scores.length - 1)); // special handling if insufficient data to calculate if(k < 2) { return scores[0]; } return scores[k - 1] + (f * (scores[k] - scores[k - 1])); } /** * DOCUMENTATION PENDING * * @param n DOCUMENTATION PENDING * * @return DOCUMENTATION PENDING */ private static String castingNum(double number,int decimal) { int indexOfDec=0; String n; int index; if(Math.ceil(number) == Math.floor(number)) { return ("" + (int) number); } else { n=""+number; indexOfDec=n.indexOf("."); index=indexOfDec+decimal+1; //log.info("NUMBER : "+n); //log.info("NUMBER LENGTH : "+n.length()); if(n.length()>index) { return n.substring(0,index); } else{ return ""+number; } } } private String castingNumForMode(String oldmode) // only show 2 decimal points for Mode { String[] tokens = oldmode.split(","); String[] roundedtokens = new String[tokens.length]; StringBuilder newModebuf = new StringBuilder(); for (int j = 0; j < tokens.length; j++) { roundedtokens[j] = castingNum(new Double(tokens[j]).doubleValue(), 2); newModebuf.append(", " + roundedtokens[j]); } String newMode = newModebuf.toString(); newMode = newMode.substring(2, newMode.length()); return newMode; } private String getType(int typeId) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); if (typeId == TypeIfc.MULTIPLE_CHOICE.intValue()) { return rc.getString("multiple_choice_sin"); } if (typeId == TypeIfc.MULTIPLE_CORRECT.intValue()) { return rc.getString("multipl_mc_ms"); } if (typeId == TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.intValue()) { return rc.getString("multipl_mc_ss"); } if (typeId == TypeIfc.MULTIPLE_CHOICE_SURVEY.intValue()) { return rb.getString("q_mult_surv"); } if (typeId == TypeIfc.TRUE_FALSE.intValue()) { return rb.getString("q_tf"); } if (typeId == TypeIfc.ESSAY_QUESTION.intValue()) { return rb.getString("q_short_ess"); } if (typeId == TypeIfc.FILE_UPLOAD.intValue()) { return rb.getString("q_fu"); } if (typeId == TypeIfc.AUDIO_RECORDING.intValue()) { return rb.getString("q_aud"); } if (typeId == TypeIfc.FILL_IN_BLANK.intValue()) { return rb.getString("q_fib"); } if (typeId == TypeIfc.MATCHING.intValue()) { return rb.getString("q_match"); } if (typeId == TypeIfc.FILL_IN_NUMERIC.intValue()) { return rb.getString("q_fin"); } if (typeId == TypeIfc.EXTENDED_MATCHING_ITEMS.intValue()) { return rb.getString("q_emi"); } if (typeId == TypeIfc.MATRIX_CHOICES_SURVEY.intValue()) { return rb.getString("q_matrix_choices_surv"); } return ""; } /** * Standard process action method. * @param ae ActionEvent * @throws AbortProcessingException */ public List getDetailedStatisticsSpreadsheetData(String publishedId) throws AbortProcessingException { log.debug("HistogramAggregate Statistics LISTENER."); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); totalBean.setPublishedId(publishedId); //String publishedId = totalBean.getPublishedId(); if (!histogramScores(bean, totalBean)) { throw new RuntimeException("failed to call histogramScores."); } ArrayList spreadsheetRows = new ArrayList(); List<HistogramQuestionScoresBean> detailedStatistics = bean.getDetailedStatistics(); spreadsheetRows.add(bean.getShowPartAndTotalScoreSpreadsheetColumns()); //spreadsheetRows.add(bean.getShowDiscriminationColumn()); boolean showDetailedStatisticsSheet; if (totalBean.getFirstItem().equals("")) { showDetailedStatisticsSheet = false; spreadsheetRows.add(showDetailedStatisticsSheet); return spreadsheetRows; } else { showDetailedStatisticsSheet = true; spreadsheetRows.add(showDetailedStatisticsSheet); } if (detailedStatistics==null || detailedStatistics.size()==0) { return spreadsheetRows; } ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ArrayList<Object> headerList = new ArrayList<Object>(); headerList = new ArrayList<Object>(); headerList.add(ExportResponsesBean.HEADER_MARKER); headerList.add(rb.getString("question")); if(bean.getRandomType()){ headerList.add("N(" + bean.getNumResponses() + ")"); }else{ headerList.add("N"); } headerList.add(rb.getString("pct_correct_of")); if (bean.getShowDiscriminationColumn()) { headerList.add(rb.getString("pct_correct_of")); headerList.add(rb.getString("pct_correct_of")); headerList.add(rb.getString("discrim_abbrev")); } headerList.add(rb.getString("frequency")); spreadsheetRows.add(headerList); headerList = new ArrayList<Object>(); headerList.add(ExportResponsesBean.HEADER_MARKER); headerList.add(""); headerList.add(""); headerList.add(rb.getString("whole_group")); if (bean.getShowDiscriminationColumn()) { headerList.add(rb.getString("upper_pct")); headerList.add(rb.getString("lower_pct")); headerList.add(""); } // No Answer headerList.add(rb.getString("no_answer")); // Label the response options A, B, C, ... int aChar = 65; for (char colHeader=65; colHeader < 65+bean.getMaxNumberOfAnswers(); colHeader++) { headerList.add(String.valueOf(colHeader)); } spreadsheetRows.add(headerList); //VULA-1948: sort the detailedStatistics list by Question Label sortQuestionScoresByLabel(detailedStatistics); Iterator detailedStatsIter = detailedStatistics.iterator(); ArrayList statsLine = null; while (detailedStatsIter.hasNext()) { HistogramQuestionScoresBean questionBean = (HistogramQuestionScoresBean)detailedStatsIter.next(); statsLine = new ArrayList(); statsLine.add(questionBean.getQuestionLabel()); Double dVal; statsLine.add(questionBean.getNumResponses()); try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrect()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrect()); } if (bean.getShowDiscriminationColumn()) { try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrectFromUpperQuartileStudents()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrectFromUpperQuartileStudents()); } try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrectFromLowerQuartileStudents()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrectFromLowerQuartileStudents()); } try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getDiscrimination()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getDiscrimination()); } } dVal = Double.parseDouble("" + questionBean.getNumberOfStudentsWithZeroAnswers()); statsLine.add(dVal); for (int i=0; i<questionBean.getHistogramBars().length; i++) { try { if (questionBean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) && !questionBean.getQuestionLabel().contains("-")) { statsLine.add(" "); } else { if (questionBean.getHistogramBars()[i].getIsCorrect()) { statsLine.add(ExportResponsesBean.FORMAT_BOLD); } dVal = Double.parseDouble("" + questionBean.getHistogramBars()[i].getNumStudents() ); statsLine.add(dVal); } } catch (NullPointerException npe) { log.warn("questionBean.getHistogramBars()[" + i + "] is null. " + npe); } } spreadsheetRows.add(statsLine); } return spreadsheetRows; } /** * This method sort the detailedStatistics List by Question Label value * * @param detailedStatistics */ private void sortQuestionScoresByLabel(List<HistogramQuestionScoresBean> detailedStatistics) { //VULA-1948: sort the detailedStatistics list by Question Label Collections.sort(detailedStatistics, new Comparator<HistogramQuestionScoresBean>() { @Override public int compare(HistogramQuestionScoresBean arg0, HistogramQuestionScoresBean arg1) { HistogramQuestionScoresBean bean1 = (HistogramQuestionScoresBean) arg0; HistogramQuestionScoresBean bean2 = (HistogramQuestionScoresBean) arg1; //first check the part number int compare = Integer.valueOf(bean1.getPartNumber()) - Integer.valueOf(bean2.getPartNumber()); if (compare != 0) { return compare; } //now check the question number int number1 = 0; int number2 = 0; //check if the question has a sub-question number, only test the question number now if(bean1.getQuestionNumber().indexOf("-") == -1){ number1 = Integer.valueOf(bean1.getQuestionNumber()); }else{ number1 = Integer.valueOf(bean1.getQuestionNumber().substring(0, bean1.getQuestionNumber().indexOf("-"))); } if(bean2.getQuestionNumber().indexOf("-") == -1){ number2 = Integer.valueOf(bean2.getQuestionNumber()); }else{ number2 = Integer.valueOf(bean2.getQuestionNumber().substring(0, bean2.getQuestionNumber().indexOf("-"))); } compare = number1 - number2; if(compare != 0){ return compare; } //Now check the sub-question number. At this stage it will be from the same question number1 = Integer.valueOf(bean1.getQuestionNumber().substring(bean1.getQuestionNumber().indexOf("-")+1)); number2 = Integer.valueOf(bean2.getQuestionNumber().substring(bean2.getQuestionNumber().indexOf("-")+1)); return number1 - number2; } }); } private List<AssessmentGradingData> filterGradingData(List<AssessmentGradingData> submissionsSortedForDiscrim, Long itemId) { List<AssessmentGradingData> submissionsForItemSortedForDiscrim = new ArrayList<AssessmentGradingData>(); for(AssessmentGradingData agd: submissionsSortedForDiscrim){ Set<ItemGradingData> itemGradings = agd.getItemGradingSet(); for(ItemGradingData igd: itemGradings){ if(igd.getPublishedItemId().equals(itemId)){ submissionsForItemSortedForDiscrim.add(agd); break; } } } return submissionsForItemSortedForDiscrim; } }
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java
package org.sakaiproject.tool.assessment.ui.listener.evaluation; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.TreeSet; import javax.faces.component.html.HtmlSelectOneMenu; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.event.ValueChangeEvent; import javax.faces.event.ValueChangeListener; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import org.hibernate.Hibernate; import org.sakaiproject.tool.assessment.api.SamigoApiFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingComparatorByScoreAndUniqueIdentifier; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentBaseIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemMetaDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.PublishedItemService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.Phase; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.PhaseStatus; import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.ExportResponsesBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramBarBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramQuestionScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.ItemBarBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.QuestionScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.util.ResourceLoader; /** * <p> * This handles the selection of the Histogram Aggregate Statistics. * </p> * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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. * * @version $Id$ */ public class HistogramListener implements ActionListener, ValueChangeListener { private static Logger log = LoggerFactory.getLogger(HistogramListener.class); //private static BeanSort bs; //private static ContextUtil cu; //private static EvaluationListenerUtil util; /** * Standard process action method. * @param ae ActionEvent * @throws AbortProcessingException */ public void processAction(ActionEvent ae) throws AbortProcessingException { log.debug("HistogramListener.processAction()"); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); if (!histogramScores(bean, totalBean)) { String publishedId = totalBean.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } log.error("Error getting statistics for assessment with published id = " + publishedId); FacesContext context = FacesContext.getCurrentInstance(); // reset histogramScoresBean, otherwise the previous assessment viewed is displayed. // note that createValueBinding seems to be deprecated and replaced by a new method in 1.2. Might need to modify this later FacesContext.getCurrentInstance().getApplication().createValueBinding("#{histogramScores}").setValue(FacesContext.getCurrentInstance(), null ); return ; } } /** * Process a value change. */ public void processValueChange(ValueChangeEvent event) { if(!HtmlSelectOneMenu.class.isInstance(event.getSource()) || event.getNewValue() == null || event.getNewValue().equals(event.getOldValue())){ return; } HtmlSelectOneMenu selectOneMenu = HtmlSelectOneMenu.class.cast(event.getSource()); if(selectOneMenu.getId() != null && selectOneMenu.getId().startsWith("allSubmissions")){ processAllSubmissionsChange(event); } } public void processAllSubmissionsChange(ValueChangeEvent event) { TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores"); String selectedvalue= (String) event.getNewValue(); if ((selectedvalue!=null) && (!selectedvalue.equals("")) ){ log.debug("changed submission pulldown "); bean.setAllSubmissions(selectedvalue); // changed for histogram score bean totalBean.setAllSubmissions(selectedvalue); // changed for total score bean questionBean.setAllSubmissions(selectedvalue); // changed for Question score bean } if (!histogramScores(bean, totalBean)) { String publishedId = totalBean.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } log.error("Error getting statistics for assessment with published id = " + publishedId); FacesContext context = FacesContext.getCurrentInstance(); FacesContext.getCurrentInstance().getApplication().createValueBinding( "#{histogramScores}").setValue(FacesContext.getCurrentInstance(), null ); return ; } } /** * Calculate the detailed statistics * * This will populate the HistogramScoresBean with the data associated with the * particular versioned assessment based on the publishedId. * * Some of this code will change when we move this to Hibernate persistence. * @param publishedId String * @param histogramScores TotalScoresBean * @return boolean true if successful */ public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) { DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery"); String publishedId = totalScores.getPublishedId(); if (publishedId.equals("0")) { publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId"); } String actionString = ContextUtil.lookupParam("actionString"); // See if this can fix SAK-16437 if (actionString != null && !actionString.equals("reviewAssessment")){ // Shouldn't come to here. The action should either be null or reviewAssessment. // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message. log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = " + AgentFacade.getAgentString()); } ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); String assessmentName = ""; histogramScores.clearLowerQuartileStudents(); histogramScores.clearUpperQuartileStudents(); String which = histogramScores.getAllSubmissions(); if (which == null && totalScores.getAllSubmissions() != null) { // use totalscore's selection which = totalScores.getAllSubmissions(); histogramScores.setAllSubmissions(which); // changed submission pulldown } histogramScores.setItemId(ContextUtil.lookupParam("itemId")); histogramScores.setHasNav(ContextUtil.lookupParam("hasNav")); GradingService delegate = new GradingService(); PublishedAssessmentService pubService = new PublishedAssessmentService(); List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which); //set the ItemGradingData manually here. or we cannot //retrieve it later. for(AssessmentGradingData agd: allscores){ agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId()))); } if (allscores.isEmpty()) { // Similar case in Bug 1537, but clicking Statistics link instead of assignment title. // Therefore, redirect the the same page. delivery.setOutcome("reviewAssessmentError"); delivery.setActionString(actionString); return true; } histogramScores.setPublishedId(publishedId); int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER; String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent"); if (isFromStudent != null && "true".equals(isFromStudent)) { callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT; } // get the Map of all users(keyed on userid) belong to the selected sections // now we only include scores of users belong to the selected sections Map useridMap = null; ArrayList scores = new ArrayList(); // only do section filter if it's published to authenticated users if (totalScores.getReleaseToAnonymous()) { scores.addAll(allscores); } else { useridMap = totalScores.getUserIdMap(callerName); Iterator allscores_iter = allscores.iterator(); while (allscores_iter.hasNext()) { AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next(); String agentid = data.getAgentId(); if (useridMap.containsKey(agentid)) { scores.add(data); } } } Iterator iter = scores.iterator(); //log.info("Has this many agents: " + scores.size()); if (!iter.hasNext()){ log.info("Students who have submitted may have been removed from this site"); return false; } // here scores contain AssessmentGradingData Map assessmentMap = getAssessmentStatisticsMap(scores); /* * find students in upper and lower quartiles * of assessment scores */ ArrayList submissionsSortedForDiscrim = new ArrayList(scores); boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue(); Collections.sort(submissionsSortedForDiscrim, new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous)); int numSubmissions = scores.size(); //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded int percent27 = numSubmissions*27/100; // rounded down if (percent27 == 0) percent27 = 1; for (int i=0; i<percent27; i++) { histogramScores.addToLowerQuartileStudents(((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId()); histogramScores.addToUpperQuartileStudents(((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions-1-i)).getAgentId()); } PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false); if (pub != null) { if (actionString != null && actionString.equals("reviewAssessment")){ if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) { // Bug 1547: If this is during review and the assessment is retracted for edit now, // set the outcome to isRetractedForEdit2 error page. delivery.setOutcome("isRetractedForEdit2"); delivery.setActionString(actionString); return true; } else { delivery.setOutcome("histogramScores"); delivery.setSecureDeliveryHTMLFragment( "" ); delivery.setBlockDelivery( false ); SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance().getSecureDeliveryServiceAPI(); if ( secureDelivery.isSecureDeliveryAvaliable() ) { String moduleId = pub.getAssessmentMetaDataByLabel( SecureDeliveryServiceAPI.MODULE_KEY ); if ( moduleId != null && ! SecureDeliveryServiceAPI.NONE_ID.equals( moduleId ) ) { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW, pub, request ); delivery.setSecureDeliveryHTMLFragment( secureDelivery.getHTMLFragment(moduleId, pub, request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale() ) ); if ( PhaseStatus.FAILURE == status ) { delivery.setOutcome( "secureDeliveryError" ); delivery.setActionString(actionString); delivery.setBlockDelivery( true ); return true; } } } } } boolean showObjectivesColumn = Boolean.parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS)); Map<String, Double> objectivesCorrect = new HashMap<String, Double>(); Map<String, Integer> objectivesCounter = new HashMap<String, Integer>(); Map<String, Double> keywordsCorrect = new HashMap<String, Double>(); Map<String, Integer> keywordsCounter = new HashMap<String, Integer>(); assessmentName = pub.getTitle(); List<? extends SectionDataIfc> parts = pub.getSectionArraySorted(); histogramScores.setAssesmentParts((List<PublishedSectionData>)parts); ArrayList info = new ArrayList(); Iterator partsIter = parts.iterator(); int secseq = 1; double totalpossible = 0; boolean hasRandompart = false; boolean isRandompart = false; String poolName = null; HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which); HashMap itemScores = new HashMap(); if (totalScores.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users itemScores.putAll(itemScoresMap); } else { if (useridMap == null) { useridMap = totalScores.getUserIdMap(callerName); } for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Long itemId = (Long) entry.getKey(); ArrayList itemScoresList = (ArrayList) entry.getValue(); ArrayList filteredItemScoresList = new ArrayList(); Iterator itemScoresIter = itemScoresList.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (itemScoresIter.hasNext()) { ItemGradingData idata = (ItemGradingData) itemScoresIter.next(); String agentid = idata.getAgentId(); if (useridMap.containsKey(agentid)) { filteredItemScoresList.add(idata); } } itemScores.put(itemId, filteredItemScoresList); } } // Iterate through the assessment parts while (partsIter.hasNext()) { SectionDataIfc section = (SectionDataIfc) partsIter.next(); String authortype = section .getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE); try{ if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL .equals(Integer.valueOf(authortype))) { hasRandompart = true; isRandompart = true; poolName = section .getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW); } else { isRandompart = false; poolName = null; } }catch(NumberFormatException e){ isRandompart = false; poolName = null; } if (section.getSequence() == null) section.setSequence(Integer.valueOf(secseq++)); String title = rb.getString("part") + " " + section.getSequence().toString(); title += ", " + rb.getString("question") + " "; List<ItemDataIfc> itemset = section.getItemArraySortedForGrading(); int seq = 1; Iterator<ItemDataIfc> itemsIter = itemset.iterator(); // Iterate through the assessment questions (items) while (itemsIter.hasNext()) { HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean(); questionScores.setNumberOfParts(parts.size()); //if this part is a randompart , then set randompart = true questionScores.setRandomType(isRandompart); questionScores.setPoolName(poolName); ItemDataIfc item = itemsIter.next(); if (showObjectivesColumn) { String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE); questionScores.setObjectives(obj); String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD); questionScores.setKeywords(key); } //String type = delegate.getTextForId(item.getTypeId()); String type = getType(item.getTypeId().intValue()); if (item.getSequence() == null) item.setSequence(Integer.valueOf(seq++)); questionScores.setPartNumber( section.getSequence().toString()); //set the question label depending on random pools and parts if(questionScores.getRandomType() && poolName != null){ if(questionScores.getNumberOfParts() > 1){ questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null)); }else{ questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null)); } }else{ if(questionScores.getNumberOfParts() > 1){ questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null)); }else{ questionScores.setQuestionLabelFormat(rb.getString("label_question", null)); } } questionScores.setQuestionNumber( item.getSequence().toString()); questionScores.setItemId(item.getItemId()); questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")"); if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question questionScores.setQuestionText(item.getLeadInText()); } else { questionScores.setQuestionText(item.getText()); } questionScores.setQuestionType(item.getTypeId().toString()); //totalpossible = totalpossible + item.getScore().doubleValue(); //ArrayList responses = null; //for each question (item) in the published assessment's current part/section determineResults(pub, questionScores, (ArrayList) itemScores .get(item.getItemId())); questionScores.setTotalScore(item.getScore().toString()); questionScores.setN(""+numSubmissions); questionScores.setItemId(item.getItemId()); Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect(); Set studentsResponded = questionScores.getStudentsResponded(); if (studentsWithAllCorrect == null || studentsResponded == null || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) { questionScores.setPercentCorrectFromUpperQuartileStudents("0"); questionScores.setPercentCorrectFromLowerQuartileStudents("0"); questionScores.setDiscrimination("0.0"); } else { int percent27ForThisQuestion = percent27; Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet(); Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet(); if(isRandompart){ //we need to calculate the 27% upper and lower //per question for the people that actually answered //this question. upperQuartileStudents = new HashSet<String>(); lowerQuartileStudents = new HashSet<String>(); percent27ForThisQuestion = questionScores.getNumResponses()*27/100; if (percent27ForThisQuestion == 0) percent27ForThisQuestion = 1; if(questionScores.getNumResponses() != 0){ //need to only get gradings for students that answered this question List<AssessmentGradingData> filteredGradings = filterGradingData(submissionsSortedForDiscrim, questionScores.getItemId()); // SAM-2228: loop control issues because of unsynchronized collection access int filteredGradingsSize = filteredGradings.size(); percent27ForThisQuestion = filteredGradingsSize*27/100; for (int i = 0; i < percent27ForThisQuestion; i++) { lowerQuartileStudents.add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId()); // upperQuartileStudents.add(((AssessmentGradingData) filteredGradings.get(filteredGradingsSize-1-i)).getAgentId()); } } } if(questionScores.getNumResponses() != 0){ int numStudentsWithAllCorrectFromUpperQuartile = 0; int numStudentsWithAllCorrectFromLowerQuartile = 0; Iterator studentsIter = studentsWithAllCorrect.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (upperQuartileStudents.contains(agentId)) { numStudentsWithAllCorrectFromUpperQuartile++; } if (lowerQuartileStudents.contains(agentId)) { numStudentsWithAllCorrectFromLowerQuartile++; } } double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile / (double) percent27ForThisQuestion) * 100d; double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile / (double) percent27ForThisQuestion) * 100d; questionScores.setPercentCorrectFromUpperQuartileStudents( Integer.toString((int) percentCorrectFromUpperQuartileStudents)); questionScores.setPercentCorrectFromLowerQuartileStudents( Integer.toString((int) percentCorrectFromLowerQuartileStudents)); double discrimination = ((double)numStudentsWithAllCorrectFromUpperQuartile - (double)numStudentsWithAllCorrectFromLowerQuartile)/(double)percent27ForThisQuestion ; // round to 2 decimals if (discrimination > 999999 || discrimination < -999999) { questionScores.setDiscrimination("NaN"); } else { discrimination = ((int) (discrimination*100.00d)) / 100.00d; questionScores.setDiscrimination(Double.toString(discrimination)); } }else{ questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na")); questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na")); questionScores.setDiscrimination(rbEval.getString("na")); } } info.add(questionScores); } // end-while - items totalpossible = pub.getTotalScore().doubleValue(); } // end-while - parts histogramScores.setInfo(info); histogramScores.setRandomType(hasRandompart); int maxNumOfAnswers = 0; List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>(); Iterator infoIter = info.iterator(); while (infoIter.hasNext()) { HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean)infoIter.next(); if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString()) || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString()) || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()) || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString()) || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString()) || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString()) || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString()) || questionScores.getQuestionType().equals("16") ) { questionScores.setShowIndividualAnswersInDetailedStatistics(true); detailedStatistics.add(questionScores); if (questionScores.getHistogramBars() != null) { maxNumOfAnswers = questionScores.getHistogramBars().length >maxNumOfAnswers ? questionScores.getHistogramBars().length : maxNumOfAnswers; } } if (showObjectivesColumn) { // Get the percentage correct by objective String obj = questionScores.getObjectives(); if (obj != null && !"".equals(obj)) { String[] objs = obj.split(","); for (int i=0; i < objs.length; i++) { // SAM-2508 set a default value to avoid the NumberFormatException issues Double pctCorrect = 0.0d; Double newAvg = 0.0d; int divisor = 1; try { if (questionScores.getPercentCorrect() != null && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) { pctCorrect = Double.parseDouble(questionScores.getPercentCorrect()); } } catch (NumberFormatException nfe) { log.error("NFE when looking at metadata and objectives", nfe); } if (objectivesCorrect.get(objs[i]) != null) { Double objCorrect = objectivesCorrect.get(objs[i]); divisor = objCorrect.intValue() + 1; newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); } else { newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue(); } objectivesCounter.put(objs[i], divisor); objectivesCorrect.put(objs[i], newAvg); } } // Get the percentage correct by keyword String key = questionScores.getKeywords(); if (key != null && !"".equals(key)) { String [] keys = key.split(","); for (int i=0; i < keys.length; i++) { if (keywordsCorrect.get(keys[i]) != null) { int divisor = keywordsCounter.get(keys[i]) + 1; Double newAvg = keywordsCorrect.get(keys[i]) + ( (Double.parseDouble(questionScores.getPercentCorrect()) - keywordsCorrect.get(keys[i]) ) / divisor); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); keywordsCounter.put(keys[i], divisor); keywordsCorrect.put(keys[i], newAvg); } else { Double newAvg = Double.parseDouble(questionScores.getPercentCorrect()); newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue(); keywordsCounter.put(keys[i], 1); keywordsCorrect.put(keys[i], newAvg); } } } } //i.e. for EMI questions we add detailed stats for the whole //question as well as for the sub-questions if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) ) { questionScores.setShowIndividualAnswersInDetailedStatistics(false); detailedStatistics.addAll(questionScores.getInfo()); Iterator subInfoIter = questionScores.getInfo().iterator(); while (subInfoIter.hasNext()) { HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter.next(); if (subQuestionScores.getHistogramBars() != null) { subQuestionScores.setN(questionScores.getN()); maxNumOfAnswers = subQuestionScores.getHistogramBars().length >maxNumOfAnswers ? subQuestionScores.getHistogramBars().length : maxNumOfAnswers; } } /* Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId()); if (numberOfStudentsWithZeroAnswers == null) { questionScores.setNumberOfStudentsWithZeroAnswers(0); } else { questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() ); } */ } } //VULA-1948: sort the detailedStatistics list by Question Label sortQuestionScoresByLabel(detailedStatistics); histogramScores.setDetailedStatistics(detailedStatistics); histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers); histogramScores.setShowObjectivesColumn(showObjectivesColumn); if (showObjectivesColumn) { List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(objectivesCorrect.entrySet()); Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() { public int compare(Entry<String, Double> e1, Entry<String, Double> e2) { return e1.getKey().compareTo(e2.getKey()); } }); histogramScores.setObjectives(objectivesList); List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(keywordsCorrect.entrySet()); Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() { public int compare(Entry<String, Double> e1, Entry<String, Double> e2) { return e1.getKey().compareTo(e2.getKey()); } }); histogramScores.setKeywords(keywordsList); } // test to see if it gets back empty map if (assessmentMap.isEmpty()) { histogramScores.setNumResponses(0); } try { BeanUtils.populate(histogramScores, assessmentMap); // quartiles don't seem to be working, workaround histogramScores.setQ1((String) assessmentMap.get("q1")); histogramScores.setQ2((String) assessmentMap.get("q2")); histogramScores.setQ3((String) assessmentMap.get("q3")); histogramScores.setQ4((String) assessmentMap.get("q4")); histogramScores.setTotalScore((String) assessmentMap .get("totalScore")); histogramScores.setTotalPossibleScore(Double .toString(totalpossible)); HistogramBarBean[] bars = new HistogramBarBean[histogramScores .getColumnHeight().length]; for (int i = 0; i < histogramScores.getColumnHeight().length; i++) { bars[i] = new HistogramBarBean(); bars[i] .setColumnHeight(Integer .toString(histogramScores .getColumnHeight()[i])); bars[i].setNumStudents(histogramScores .getNumStudentCollection()[i]); bars[i].setRangeInfo(histogramScores .getRangeCollection()[i]); //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]); } histogramScores.setHistogramBars(bars); /////////////////////////////////////////////////////////// // START DEBUGGING /* log.info("TESTING ASSESSMENT MAP"); log.info("assessmentMap: =>"); log.info(assessmentMap); log.info("--------------------------------------------"); log.info("TESTING TOTALS HISTOGRAM FORM"); log.info( "HistogramScoresForm Form: =>\n" + "bean.getMean()=" + bean.getMean() + "\n" + "bean.getColumnHeight()[0] (first elem)=" + bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" + bean.getInterval() + "\n" + "bean.getLowerQuartile()=" + bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" + bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() + "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" + "bean.getNumResponses()=" + bean.getNumResponses() + "\n" + "bean.getNumStudentCollection()=" + bean.getNumStudentCollection() + "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" + bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" + "bean.getQ4()=" + bean.getQ4()); log.info("--------------------------------------------"); */ // END DEBUGGING CODE /////////////////////////////////////////////////////////// } catch (IllegalAccessException e) { log.warn("IllegalAccessException: unable to populate bean" + e); } catch (InvocationTargetException e) { log.warn("InvocationTargetException: unable to populate bean" + e); } histogramScores.setAssessmentName(assessmentName); } else { log.error("pub is null. publishedId = " + publishedId); return false; } return true; } /** * For each question (item) in the published assessment's current part/section * determine the results by calculating statistics for whole question or * individual answers depending on the question type * @param pub * @param qbean * @param itemScores */ private void determineResults(PublishedAssessmentIfc pub, HistogramQuestionScoresBean qbean, ArrayList<ItemGradingData> itemScores) { if (itemScores == null) itemScores = new ArrayList<ItemGradingData>(); int responses = 0; Set<Long> assessmentGradingIds = new HashSet<Long>(); int numStudentsWithZeroAnswers = 0; for (ItemGradingData itemGradingData: itemScores) { //only count the unique questions answers if(!assessmentGradingIds.contains(itemGradingData.getAssessmentGradingId())){ responses++; assessmentGradingIds.add(itemGradingData.getAssessmentGradingId()); if (itemGradingData.getSubmittedDate() == null) { numStudentsWithZeroAnswers++; } } } qbean.setNumResponses(responses); qbean.setNumberOfStudentsWithZeroAnswers(numStudentsWithZeroAnswers); if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString()) || // mcsc qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString()) || // mcmcms qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString()) || // mcmcss qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString()) || // mc survey qbean.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString()) || // tf qbean.getQuestionType().equals(TypeIfc.MATCHING.toString()) || // matching qbean.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()) || // Fill in the blank qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) || // Extended Matching Items qbean.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString()) || // Numeric Response qbean.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString()) || // CALCULATED_QUESTION qbean.getQuestionType().equals(TypeIfc.IMAGEMAP_QUESTION.toString()) || // IMAGEMAP_QUESTION qbean.getQuestionType().equals(TypeIfc.MATRIX_CHOICES_SURVEY.toString())) // matrix survey doAnswerStatistics(pub, qbean, itemScores); if (qbean.getQuestionType().equals(TypeIfc.ESSAY_QUESTION.toString()) || // essay qbean.getQuestionType().equals(TypeIfc.FILE_UPLOAD.toString()) || // file upload qbean.getQuestionType().equals(TypeIfc.AUDIO_RECORDING.toString())) // audio recording doScoreStatistics(qbean, itemScores); } /** * For each question where statistics are required for seperate answers, * this method calculates the answer statistics by calling a different * getXXXScores() method for each question type. * @param pub * @param qbean * @param scores */ private void doAnswerStatistics(PublishedAssessmentIfc pub, HistogramQuestionScoresBean qbean, List<ItemGradingData> scores) { // Don't return here. This will cause questions to be displayed inconsistently on the stats page // if (scores.isEmpty()) // { // qbean.setHistogramBars(new HistogramBarBean[0]); // qbean.setNumResponses(0); // qbean.setPercentCorrect(rb.getString("no_responses")); // return; // } PublishedAssessmentService pubService = new PublishedAssessmentService(); PublishedItemService pubItemService = new PublishedItemService(); //build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService.preparePublishedItemHash(pub); HashMap publishedItemTextHash = pubService.preparePublishedItemTextHash(pub); HashMap publishedAnswerHash = pubService.preparePublishedAnswerHash(pub); // re-attach session and load all lazy loaded parent/child stuff // Set<Long> publishedAnswerHashKeySet = publishedAnswerHash.keySet(); // // for(Long key : publishedAnswerHashKeySet) { // AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(key); // // if (! Hibernate.isInitialized(answer.getChildAnswerSet())) { // pubItemService.eagerFetchAnswer(answer); // } // } //int numAnswers = 0; ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(qbean.getItemId()); List text = item.getItemTextArraySorted(); List answers = null; //keys number of correct answers required by sub-question (ItemText) HashMap emiRequiredCorrectAnswersCount = null; if (qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) { //EMI emiRequiredCorrectAnswersCount = new HashMap(); answers = new ArrayList(); for (int i=0; i<text.size(); i++) { ItemTextIfc iText = (ItemTextIfc) publishedItemTextHash.get(((ItemTextIfc) text.toArray()[i]).getId()); if (iText.isEmiQuestionItemText()) { boolean requireAllCorrectAnswers = true; int numCorrectAnswersRequired = 0; if (iText.getRequiredOptionsCount()!=null && iText.getRequiredOptionsCount().intValue()>0) { requireAllCorrectAnswers = false; numCorrectAnswersRequired = iText.getRequiredOptionsCount().intValue(); } if (iText.getAnswerArraySorted() == null) continue; Iterator ansIter = iText.getAnswerArraySorted().iterator(); while (ansIter.hasNext()) { AnswerIfc answer = (AnswerIfc)ansIter.next(); answers.add(answer); if (requireAllCorrectAnswers && answer.getIsCorrect()) { numCorrectAnswersRequired++; } } emiRequiredCorrectAnswersCount.put(iText.getId(), Integer.valueOf(numCorrectAnswersRequired)); } } } else if (!qbean.getQuestionType().equals(TypeIfc.MATCHING.toString())) // matching { ItemTextIfc firstText = (ItemTextIfc) publishedItemTextHash.get(((ItemTextIfc) text.toArray()[0]).getId()); answers = firstText.getAnswerArraySorted(); } if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())) // mcsc getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())) // mcmc getFIBMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())) getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())) getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())) // tf getTFMCScores(publishedAnswerHash, scores, qbean, answers); else if ((qbean.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString()))||(qbean.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())) ) getFIBMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); //else if (qbean.getQuestionType().equals("11")) // getFINMCMCScores(publishedItemHash, publishedAnswerHash, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MATCHING.toString())) getMatchingScores(publishedItemTextHash, publishedAnswerHash, scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) getEMIScores(publishedItemHash, publishedAnswerHash, emiRequiredCorrectAnswersCount, scores, qbean, answers); else if (qbean.getQuestionType().equals(TypeIfc.MATRIX_CHOICES_SURVEY.toString())) // matrix survey question getMatrixSurveyScores(publishedItemTextHash, publishedAnswerHash, scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())) // CALCULATED_QUESTION getCalculatedQuestionScores(scores, qbean, text); else if (qbean.getQuestionType().equals(TypeIfc.IMAGEMAP_QUESTION.toString())) // IMAGEMAP_QUESTION getImageMapQuestionScores(publishedItemTextHash, publishedAnswerHash, (ArrayList) scores, qbean, (ArrayList) text); } /** * calculates statistics for EMI questions */ private void getEMIScores(HashMap publishedItemHash, HashMap publishedAnswerHash, HashMap emiRequiredCorrectAnswersCount, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); // Answers keyed by answer-id HashMap answersById = new HashMap(); //keys the number of student responses selecting a particular answer //by the Answer ID HashMap results = new HashMap(); //keys Answer-IDs by subQuestion/ItemTextSequence-answerSequence (concatenated) HashMap sequenceMap = new HashMap(); //list of answers for each sub-question/ItemText ArrayList subQuestionAnswers = null; //Map which keys above lists by the sub-question/ItemText sequence HashMap subQuestionAnswerMap = new HashMap(); //Create a Map where each Sub-Question's Answers-ArrayList //is keyed by sub-question and answer sequence Iterator iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); answersById.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getItemText().getSequence() + "-" + answer.getSequence(), answer.getId()); Long subQuestionSequence = answer.getItemText().getSequence(); Object subSeqAns = subQuestionAnswerMap.get(subQuestionSequence); if (subSeqAns == null) { subQuestionAnswers = new ArrayList(); subQuestionAnswerMap.put(subQuestionSequence, subQuestionAnswers); } else { subQuestionAnswers = (ArrayList) subSeqAns; } subQuestionAnswers.add(answer); } //Iterate through the student answers (ItemGradingData) iter = scores.iterator(); //Create a map that keys all the responses/answers (ItemGradingData) //for this question from a specific student (assessment) //by the id of that assessment (AssessmentGradingData) HashMap responsesPerStudentPerQuestionMap = new HashMap(); //and do the same for seperate sub-questions HashMap responsesPerStudentPerSubQuestionMap = new HashMap(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); //Get the published answer that corresponds to the student's reponse AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); //This should always be the case as only valid responses //from the list of available options are allowed if (answer != null) { // log.info("Gopal: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter for the number of responses that select this published answer try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); } //If this published answer has not been selected before if (num == null) num = Integer.valueOf(0); //Now create a map that keys all the responses (ItemGradingData) //for this question from a specific student (or assessment) //by the id of that assessment (AssessmentGradingData) ArrayList studentResponseList = (ArrayList) responsesPerStudentPerQuestionMap .get(data.getAssessmentGradingId()); if (studentResponseList == null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); responsesPerStudentPerQuestionMap.put(data.getAssessmentGradingId(), studentResponseList); //Do the same for the sub-questions String key = data.getAssessmentGradingId() + "-" + answer.getItemText().getId(); ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap .get(key); if (studentResponseListForSubQuestion == null) { studentResponseListForSubQuestion = new ArrayList(); } studentResponseListForSubQuestion.add(data); responsesPerStudentPerSubQuestionMap.put(key, studentResponseListForSubQuestion); results.put(answer.getId(), Integer.valueOf( num.intValue() + 1)); } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; //List of "ItemText.sequence-Answer.sequence" List<String> sequenceList = new ArrayList<String>(); iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getItemText().getSequence() + "-" + answer.getSequence()); } // sort the sequence Collections.sort(sequenceList, new Comparator<String>(){ public int compare(String o1, String o2) { Integer a1 = Integer.valueOf(o1.substring(0, o1.indexOf("-"))); Integer a2 = Integer.valueOf(o2.substring(0, o1.indexOf("-"))); int val = a1.compareTo(a2); if(val != 0){ return val; } a1 = Integer.valueOf(o1.substring(o1.indexOf("-")+1)); a2 = Integer.valueOf(o2.substring(o1.indexOf("-")+1)); return a1.compareTo(a2); } }); // iter = results.keySet().iterator(); iter = sequenceList.iterator(); int i = 0; int responses = 0; int correctresponses = 0; while (iter.hasNext()) { String sequenceId = (String) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) answersById.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); if (answer != null) { bars[i].setSubQuestionSequence(answer.getItemText().getSequence()); if (answer.getItem().getIsAnswerOptionsSimple()) { bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel() + " " + answer.getText()); } else { //rich text or attachment options bars[i].setLabel(answer.getItemText().getSequence() + ". " + answer.getLabel()); } if (answer.getLabel().equals("A")) { String title = rb.getString("item") + " " + answer.getItemText().getSequence(); String text = answer.getItemText().getText(); if (text != null && !text.equals(null)) { title += " : " + text; bars[i].setTitle(title); } } bars[i].setIsCorrect(answer.getIsCorrect()); } bars[i].setNumStudentsText(num + " " + rb.getString("responses")); bars[i].setNumStudents(num); i++; }// end while responses = responsesPerStudentPerQuestionMap.size(); //Determine the number of students with all correct responses for the whole question for (Iterator it = responsesPerStudentPerQuestionMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // iterate through the results for one student // for this question (qbean) while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData) listiter.next(); // only answered choices are created in the // ItemGradingData_T, so we need to check // if # of checkboxes the student checked is == the number // of correct answers // otherwise if a student only checked one of the multiple // correct answers, // it would count as a correct response try { int corranswers = 0; Iterator answeriter = answers.iterator(); while (answeriter.hasNext()) { AnswerIfc answerchoice = (AnswerIfc) answeriter .next(); if (answerchoice.getIsCorrect().booleanValue()) { corranswers++; } } if (resultsForOneStudent.size() != corranswers) { hasIncorrect = true; break; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "error calculating emi question."); } // now check each answer AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // end for - number of students with all correct responses for the whole question // NEW int[] heights = calColumnHeight(numarray, responses); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch(NullPointerException npe) { log.warn("null column height " + npe); } } qbean.setHistogramBars(bars); qbean.setNumResponses(responses); if (responses > 0) qbean.setPercentCorrect(Integer.toString((int) (((double) correctresponses / (double) responses) * 100))); HashMap numStudentsWithAllCorrectPerSubQuestion = new HashMap(); HashMap studentsWithAllCorrectPerSubQuestion = new HashMap(); HashMap studentsRespondedPerSubQuestion = new HashMap(); Iterator studentSubquestionResponseKeyIter = responsesPerStudentPerSubQuestionMap.keySet().iterator(); while (studentSubquestionResponseKeyIter.hasNext()) { String key = (String)studentSubquestionResponseKeyIter.next(); ArrayList studentResponseListForSubQuestion = (ArrayList) responsesPerStudentPerSubQuestionMap .get(key); if (studentResponseListForSubQuestion != null && !studentResponseListForSubQuestion.isEmpty()) { ItemGradingData response1 = (ItemGradingData)studentResponseListForSubQuestion.get(0); Long subQuestionId = ((AnswerIfc)publishedAnswerHash.get(response1.getPublishedAnswerId())).getItemText().getId(); Set studentsResponded = (Set)studentsRespondedPerSubQuestion.get(subQuestionId); if (studentsResponded == null) studentsResponded = new TreeSet(); studentsResponded.add(response1.getAgentId()); studentsRespondedPerSubQuestion.put(subQuestionId, studentsResponded); boolean hasIncorrect = false; //numCorrectSubQuestionAnswers = (Integer) correctAnswersPerSubQuestion.get(subQuestionId); Integer numCorrectSubQuestionAnswers = (Integer) emiRequiredCorrectAnswersCount.get(subQuestionId); if (studentResponseListForSubQuestion.size() < numCorrectSubQuestionAnswers.intValue()) { hasIncorrect = true; continue; } //now check each answer Iterator studentResponseIter = studentResponseListForSubQuestion.iterator(); while (studentResponseIter.hasNext()) { ItemGradingData response = (ItemGradingData)studentResponseIter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(response .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } if (hasIncorrect) continue; Integer numWithAllCorrect = (Integer)numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (numWithAllCorrect == null) { numWithAllCorrect = Integer.valueOf(0); } numStudentsWithAllCorrectPerSubQuestion.put(subQuestionId, Integer.valueOf(numWithAllCorrect.intValue() + 1)); Set studentsWithAllCorrect = (Set)studentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (studentsWithAllCorrect == null) studentsWithAllCorrect = new TreeSet(); studentsWithAllCorrect.add(response1.getAgentId()); studentsWithAllCorrectPerSubQuestion.put(subQuestionId, studentsWithAllCorrect); } } //Map ItemText sequences to Ids HashMap itemTextSequenceIdMap = new HashMap(); Iterator answersIter = answers.iterator(); while (answersIter.hasNext()) { AnswerIfc answer = (AnswerIfc)answersIter.next(); itemTextSequenceIdMap.put(answer.getItemText().getSequence(), answer.getItemText().getId()); } //Now select the the bars for each sub-questions Set subQuestionKeySet = subQuestionAnswerMap.keySet(); ArrayList subQuestionKeyList = new ArrayList(); subQuestionKeyList.addAll(subQuestionKeySet); Collections.sort(subQuestionKeyList); Iterator subQuestionIter = subQuestionKeyList.iterator(); ArrayList subQuestionInfo = new ArrayList(); //List of sub-question HistogramQuestionScoresBeans - for EMI sub-questions // Iterate through the assessment questions (items) while (subQuestionIter.hasNext()) { Long subQuestionSequence = (Long)subQuestionIter.next(); //While qbean is the HistogramQuestionScoresBean for the entire question //questionScores are the HistogramQuestionScoresBeans for each sub-question HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean(); questionScores.setSubQuestionSequence(subQuestionSequence); // Determine the number of bars (possible answers) for this sub-question int numBars = 0; for (int j=0; j<bars.length; j++) { if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) { numBars++; } } //Now create an array of that size //and populate it with the bars for this sub-question HistogramBarBean[] subQuestionBars = new HistogramBarBean[numBars]; int subBar = 0; for (int j=0; j<bars.length; j++) { if (bars[j].getSubQuestionSequence().equals(subQuestionSequence)) { subQuestionBars[subBar++]=bars[j]; } } questionScores.setShowIndividualAnswersInDetailedStatistics(true); questionScores.setHistogramBars(subQuestionBars); questionScores.setNumberOfParts(qbean.getNumberOfParts()); //if this part is a randompart , then set randompart = true questionScores.setRandomType(qbean.getRandomType()); questionScores.setPartNumber(qbean.getPartNumber()); questionScores.setQuestionNumber(qbean.getQuestionNumber()+"-"+subQuestionSequence); questionScores.setQuestionText(qbean.getQuestionText()); questionScores.setQuestionType(qbean.getQuestionType()); questionScores.setN(qbean.getN()); questionScores.setItemId(qbean.getItemId()); //This boild down to the number of AssessmentGradingData //So should be the same for whole and sub questions questionScores.setNumResponses(qbean.getNumResponses()); Long subQuestionId = (Long)itemTextSequenceIdMap.get(subQuestionSequence); if (questionScores.getNumResponses() > 0) { Integer numWithAllCorrect = (Integer)numStudentsWithAllCorrectPerSubQuestion.get(subQuestionId); if (numWithAllCorrect != null) correctresponses = numWithAllCorrect.intValue(); questionScores.setPercentCorrect(Integer.toString((int) (((double) correctresponses / (double) responses) * 100))); } Set studentsWithAllCorrect = (Set)studentsWithAllCorrectPerSubQuestion.get(subQuestionId); questionScores.setStudentsWithAllCorrect(studentsWithAllCorrect); Set studentsResponded = (Set)studentsRespondedPerSubQuestion.get(subQuestionId); questionScores.setStudentsResponded(studentsResponded); subQuestionAnswers = (ArrayList) subQuestionAnswerMap.get(subQuestionSequence); Iterator answerIter = subQuestionAnswers.iterator(); Double totalScore = new Double(0); while (answerIter.hasNext()) { AnswerIfc subQuestionAnswer = (AnswerIfc) answerIter.next(); totalScore += (subQuestionAnswer==null||subQuestionAnswer.getScore()==null?0.0:subQuestionAnswer.getScore()); } questionScores.setTotalScore(totalScore.toString()); HistogramScoresBean histogramScores = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); Iterator keys = responsesPerStudentPerSubQuestionMap.keySet().iterator(); int numSubmissions = 0; while (keys.hasNext()) { String assessmentAndSubquestionId = (String)keys.next(); if (assessmentAndSubquestionId.endsWith("-"+subQuestionId)) numSubmissions++; } int percent27 = numSubmissions*27/100; // rounded down if (percent27 == 0) percent27 = 1; studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect(); studentsResponded = questionScores.getStudentsResponded(); if (studentsWithAllCorrect == null || studentsResponded == null || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) { questionScores.setPercentCorrectFromUpperQuartileStudents("0"); questionScores.setPercentCorrectFromLowerQuartileStudents("0"); questionScores.setDiscrimination("0.0"); } else { int numStudentsWithAllCorrectFromUpperQuartile = 0; int numStudentsWithAllCorrectFromLowerQuartile = 0; Iterator studentsIter = studentsWithAllCorrect.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (histogramScores.isUpperQuartileStudent(agentId)) { numStudentsWithAllCorrectFromUpperQuartile++; } if (histogramScores.isLowerQuartileStudent(agentId)) { numStudentsWithAllCorrectFromLowerQuartile++; } } int numStudentsRespondedFromUpperQuartile = 0; int numStudentsRespondedFromLowerQuartile = 0; studentsIter = studentsResponded.iterator(); while (studentsIter.hasNext()) { String agentId = (String) studentsIter.next(); if (histogramScores.isUpperQuartileStudent(agentId)) { numStudentsRespondedFromUpperQuartile++; } if (histogramScores.isLowerQuartileStudent(agentId)) { numStudentsRespondedFromLowerQuartile++; } } double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile / (double) percent27) * 100d; double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile / (double) percent27) * 100d; questionScores.setPercentCorrectFromUpperQuartileStudents( Integer.toString((int) percentCorrectFromUpperQuartileStudents)); questionScores.setPercentCorrectFromLowerQuartileStudents( Integer.toString((int) percentCorrectFromLowerQuartileStudents)); double numResponses = (double)questionScores.getNumResponses(); double discrimination = ((double)numStudentsWithAllCorrectFromUpperQuartile - (double)numStudentsWithAllCorrectFromLowerQuartile)/(double)percent27 ; // round to 2 decimals if (discrimination > 999999 || discrimination < -999999) { questionScores.setDiscrimination("NaN"); } else { discrimination = ((int) (discrimination*100.00)) / 100.00; questionScores.setDiscrimination(Double.toString(discrimination)); } } subQuestionInfo.add(questionScores); } // end-while - items qbean.setInfo(subQuestionInfo); } private void getFIBMCMCScores(HashMap publishedItemHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); HashMap texts = new HashMap(); Iterator iter = answers.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap = new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getSequence(), answer.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { // log.info("Rachel: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); } if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList) numStudentRespondedMap .get(data.getAssessmentGradingId()); if (studentResponseList == null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); // we found a response, and got the existing num , now update // one if ((qbean.getQuestionType().equals("8")) || (qbean.getQuestionType().equals("11"))) { // for fib we only count the number of correct responses Double autoscore = data.getAutoScore(); if (!(Double.valueOf(0)).equals(autoscore)) { results.put(answer.getId(), Integer.valueOf( num.intValue() + 1)); } } else { // for mc, we count the number of all responses results .put(answer.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getSequence()); } Collections.sort(sequenceList); // iter = results.keySet().iterator(); iter = sequenceList.iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) texts.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); if (answer != null) bars[i].setLabel(answer.getText()); // this doens't not apply to fib , do not show checkmarks for FIB if (!(qbean.getQuestionType().equals("8")) && !(qbean.getQuestionType().equals("11")) && answer != null) { bars[i].setIsCorrect(answer.getIsCorrect()); } if ((num > 1) || (num == 0)) { bars[i].setNumStudentsText(num + " " + rb.getString("responses")); } else { bars[i] .setNumStudentsText(num + " " + rb.getString("response")); } bars[i].setNumStudents(num); i++; } for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // iterate through the results for one student // for this question (qbean) while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData) listiter.next(); if ((qbean.getQuestionType().equals("8")) || (qbean.getQuestionType().equals("11"))) { // TODO: we are checking to see if the score is > 0, this // will not work if the question is worth 0 points. // will need to verify each answer individually. Double autoscore = item.getAutoScore(); if ((Double.valueOf(0)).equals(autoscore)) { hasIncorrect = true; break; } } else if (qbean.getQuestionType().equals("2")) { // mcmc // only answered choices are created in the // ItemGradingData_T, so we need to check // if # of checkboxes the student checked is == the number // of correct answers // otherwise if a student only checked one of the multiple // correct answers, // it would count as a correct response try { List itemTextArray = ((ItemDataIfc) publishedItemHash .get(item.getPublishedItemId())) .getItemTextArraySorted(); List answerArray = ((ItemTextIfc) itemTextArray .get(0)).getAnswerArraySorted(); int corranswers = 0; Iterator answeriter = answerArray.iterator(); while (answeriter.hasNext()) { AnswerIfc answerchoice = (AnswerIfc) answeriter .next(); if (answerchoice.getIsCorrect().booleanValue()) { corranswers++; } } if (resultsForOneStudent.size() != corranswers) { hasIncorrect = true; break; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "error calculating mcmc question."); } // now check each answer in MCMC AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item .getPublishedAnswerId()); if (answer != null && (answer.getIsCorrect() == null || (!answer .getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch(NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean .setPercentCorrect(Integer .toString((int) (((double) correctresponses / (double) qbean.getNumResponses()) * 100))); } /* * private void getFINMCMCScores(HashMap publishedItemHash, HashMap * publishedAnswerHash, ArrayList scores, HistogramQuestionScoresBean qbean, * ArrayList answers) { HashMap texts = new HashMap(); Iterator iter = * answers.iterator(); HashMap results = new HashMap(); HashMap * numStudentRespondedMap= new HashMap(); while (iter.hasNext()) { AnswerIfc * answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); * results.put(answer.getId(), Integer.valueOf(0)); } iter = scores.iterator(); * while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) * iter.next(); AnswerIfc answer = (AnswerIfc) * publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer != null) { * //log.info("Rachel: looking for " + answer.getId()); // found a response * Integer num = null; // num is a counter try { // we found a response, now * get existing count from the hashmap num = (Integer) * results.get(answer.getId()); * * } catch (Exception e) { log.warn("No results for " + answer.getId()); } * if (num == null) num = Integer.valueOf(0); * * ArrayList studentResponseList = * (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if * (studentResponseList==null) { studentResponseList = new ArrayList(); } * studentResponseList.add(data); * numStudentRespondedMap.put(data.getAssessmentGradingId(), * studentResponseList); // we found a response, and got the existing num , * now update one if (qbean.getQuestionType().equals("11")) { // for fib we * only count the number of correct responses Double autoscore = * data.getAutoScore(); if (!(new Double(0)).equals(autoscore)) { * results.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); } } else { // * for mc, we count the number of all responses results.put(answer.getId(), * Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new * HistogramBarBean[results.keySet().size()]; int[] numarray = new * int[results.keySet().size()]; iter = results.keySet().iterator(); int i = * 0; int responses = 0; int correctresponses = 0; while (iter.hasNext()) { * Long answerId = (Long) iter.next(); AnswerIfc answer = (AnswerIfc) * texts.get(answerId); int num = ((Integer) * results.get(answerId)).intValue(); numarray[i] = num; bars[i] = new * HistogramBarBean(); if(answer != null) * bars[i].setLabel(answer.getText()); * // this doens't not apply to fib , do not show checkmarks for FIB if * (!qbean.getQuestionType().equals("11") && answer != null) { * bars[i].setIsCorrect(answer.getIsCorrect()); } * * * if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " Responses"); } * else { bars[i].setNumStudentsText(num + " Response"); * } bars[i].setNumStudents(num); i++; } * * * responses = numStudentRespondedMap.size(); Iterator mapiter = * numStudentRespondedMap.keySet().iterator(); while (mapiter.hasNext()) { * Long assessmentGradingId= (Long)mapiter.next(); ArrayList * resultsForOneStudent = * (ArrayList)numStudentRespondedMap.get(assessmentGradingId); boolean * hasIncorrect = false; Iterator listiter = * resultsForOneStudent.iterator(); while (listiter.hasNext()) { * ItemGradingData item = (ItemGradingData)listiter.next(); if * (qbean.getQuestionType().equals("11")) { Double autoscore = * item.getAutoScore(); if (!(new Double(0)).equals(autoscore)) { * hasIncorrect = true; break; } } else if * (qbean.getQuestionType().equals("2")) { * // only answered choices are created in the ItemGradingData_T, so we * need to check // if # of checkboxes the student checked is == the number * of correct answers // otherwise if a student only checked one of the * multiple correct answers, // it would count as a correct response * * try { ArrayList itemTextArray = * ((ItemDataIfc)publishedItemHash.get(item.getPublishedItemId())).getItemTextArraySorted(); * ArrayList answerArray = * ((ItemTextIfc)itemTextArray.get(0)).getAnswerArraySorted(); * * int corranswers = 0; Iterator answeriter = answerArray.iterator(); while * (answeriter.hasNext()){ AnswerIfc answerchoice = (AnswerIfc) * answeriter.next(); if (answerchoice.getIsCorrect().booleanValue()){ * corranswers++; } } if (resultsForOneStudent.size() != corranswers){ * hasIncorrect = true; break; } } catch (Exception e) { * e.printStackTrace(); throw new RuntimeException("error calculating mcmc * question."); } * // now check each answer in MCMC * * AnswerIfc answer = (AnswerIfc) * publishedAnswerHash.get(item.getPublishedAnswerId()); if ( answer != null && * (answer.getIsCorrect() == null || * (!answer.getIsCorrect().booleanValue()))) { hasIncorrect = true; break; } } } * if (!hasIncorrect) { correctresponses = correctresponses + 1; } } //NEW * int[] heights = calColumnHeight(numarray,responses); // int[] heights = * calColumnHeight(numarray); for (i=0; i<bars.length; i++) * bars[i].setColumnHeight(Integer.toString(heights[i])); * qbean.setHistogramBars(bars); qbean.setNumResponses(responses); if * (responses > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) * correctresponses/(double) responses) * 100))); } */ private void getTFMCScores(HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List answers) { ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); HashMap texts = new HashMap(); Iterator iter = answers.iterator(); HashMap results = new HashMap(); HashMap sequenceMap = new HashMap(); // create the lookup maps while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); texts.put(answer.getId(), answer); results.put(answer.getId(), Integer.valueOf(0)); sequenceMap.put(answer.getSequence(), answer.getId()); } // find the number of responses (ItemGradingData) for each answer iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { // log.info("Rachel: looking for " + answer.getId()); // found a response Integer num = null; // num is a counter try { // we found a response, now get existing count from the // hashmap num = (Integer) results.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); e.printStackTrace(); } if (num == null) num = Integer.valueOf(0); // we found a response, and got the existing num , now update // one // check here for the other bug about non-autograded items // having 1 even with no responses results.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); // this should work because for tf/mc(single) // questions, there should be at most // one submitted answer per student/assessment if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { qbean.addStudentWithAllCorrect(data.getAgentId()); } qbean.addStudentResponded(data.getAgentId()); } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); // get an arraylist of answer sequences iter = answers.iterator(); while (iter.hasNext()) { AnswerIfc answer = (AnswerIfc) iter.next(); sequenceList.add(answer.getSequence()); } // sort the sequences Collections.sort(sequenceList); iter = sequenceList.iterator(); // iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; // find answers sorted by sequence while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long answerId = (Long) sequenceMap.get(sequenceId); AnswerIfc answer = (AnswerIfc) texts.get(answerId); int num = ((Integer) results.get(answerId)).intValue(); // set i to be the sequence, so that the answer choices will be in // the right order on Statistics page , see Bug SAM-440 i = answer.getSequence().intValue() - 1; numarray[i] = num; bars[i] = new HistogramBarBean(); if (qbean.getQuestionType().equals("4")) { // true-false String origText = answer.getText(); String text = ""; if ("true".equals(origText)) { text = rb.getString("true_msg"); } else { text = rb.getString("false_msg"); } bars[i].setLabel(text); } else { bars[i].setLabel(answer.getText()); } bars[i].setIsCorrect(answer.getIsCorrect()); if ((num > 1) || (num == 0)) { bars[i].setNumStudentsText(num + " " + rb.getString("responses")); } else { bars[i] .setNumStudentsText(num + " " + rb.getString("response")); } bars[i].setNumStudents(num); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { correctresponses += num; } // i++; } // NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i = 0; i < bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean .setPercentCorrect(Integer .toString((int) (((double) correctresponses / (double) qbean.getNumResponses()) * 100))); } private void getCalculatedQuestionScores(List<ItemGradingData> scores, HistogramQuestionScoresBean qbean, List labels) { final String CORRECT = "Correct"; final String INCORRECT = "Incorrect"; final int COLUMN_MAX_HEIGHT = 600; ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); // count incorrect and correct to support column height calculation Map<String, Integer> results = new HashMap<String, Integer>(); results.put(CORRECT, Integer.valueOf(0)); results.put(INCORRECT, Integer.valueOf(0)); for (ItemGradingData score : scores) { if (score.getAutoScore() != null && score.getAutoScore() > 0) { Integer value = results.get(CORRECT); results.put(CORRECT, ++value); } else { Integer value = results.get(INCORRECT); results.put(INCORRECT, ++value); } } // build the histogram bar for correct/incorrect answers List<HistogramBarBean> barList = new ArrayList<HistogramBarBean>(); for (Map.Entry<String, Integer> entry : results.entrySet()) { HistogramBarBean bar = new HistogramBarBean(); bar.setLabel(entry.getKey()); bar.setNumStudents(entry.getValue()); if (entry.getValue() > 1) { bar.setNumStudentsText(entry.getValue() + " " + rb.getString("correct_responses")); } else { bar.setNumStudentsText(entry.getValue() + " " + rc.getString("correct_response")); } bar.setNumStudentsText(entry.getValue() + " " + entry.getKey()); bar.setIsCorrect(entry.getKey().equals(CORRECT)); int height = 0; if (scores.size() > 0) { height = COLUMN_MAX_HEIGHT * entry.getValue() / scores.size(); } bar.setColumnHeight(Integer.toString(height)); barList.add(bar); } HistogramBarBean[] bars = new HistogramBarBean[barList.size()]; bars = barList.toArray(bars); qbean.setHistogramBars(bars); // store any assessment grading ID's that are incorrect. // this will allow us to calculate % Students All correct by giving // us a count of assessmnets that had an incorrect answer Set<Long> assessmentQuestionIncorrect = new HashSet<Long>(); for (ItemGradingData score : scores) { if (score.getAutoScore() == null || score.getAutoScore() == 0) { assessmentQuestionIncorrect.add(score.getAssessmentGradingId()); } } if (qbean.getNumResponses() > 0) { int correct = qbean.getNumResponses() - assessmentQuestionIncorrect.size(); int total = qbean.getNumResponses(); double percentCorrect = ((double) correct / (double) total) * 100; String percentCorrectStr = Integer.toString((int)percentCorrect); qbean.setPercentCorrect(percentCorrectStr); } } private void getImageMapQuestionScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, ArrayList scores, HistogramQuestionScoresBean qbean, ArrayList labels) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); HashMap texts = new HashMap(); Iterator iter = labels.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap= new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); results.put(label.getId(), Integer.valueOf(0)); sequenceMap.put(label.getSequence(), label.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); ItemTextIfc text = (ItemTextIfc) publishedItemTextHash.get(data.getPublishedItemTextId()); if (text != null) { Integer num = (Integer) results.get(text.getId()); if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); //if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) if (data.getIsCorrect() != null && data.getIsCorrect().booleanValue()) // only store correct responses in the results { results.put(text.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = labels.iterator(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); sequenceList.add(label.getSequence()); } Collections.sort(sequenceList); iter = sequenceList.iterator(); //iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long textId = (Long) sequenceMap.get(sequenceId); ItemTextIfc text = (ItemTextIfc) texts.get(textId); int num = ((Integer) results.get(textId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); bars[i].setLabel(text.getText()); bars[i].setNumStudents(num); if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " " +rb.getString("correct_responses")); } else { bars[i].setNumStudentsText(num + " " +rc.getString("correct_response")); } i++; } // now calculate correctresponses // correctresponses = # of students who got all answers correct, for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // numStudentRespondedMap only stores correct answers, so now we need to // check to see if # of rows in itemgradingdata_t == labels.size() // otherwise if a student only answered one correct answer and // skipped the rest, it would count as a correct response while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData)listiter.next(); if (resultsForOneStudent.size()!= labels.size()){ hasIncorrect = true; break; } // now check each answer in Matching //AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item.getPublishedAnswerId()); if (item.getIsCorrect() == null || (!item.getIsCorrect().booleanValue())) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; // gopalrc - Nov 2007 qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } // gopalrc - Dec 2007 qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } //NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i=0; i<bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) correctresponses/(double) qbean.getNumResponses()) * 100))); } private void getMatchingScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List labels) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); HashMap texts = new HashMap(); Iterator iter = labels.iterator(); HashMap results = new HashMap(); HashMap numStudentRespondedMap= new HashMap(); HashMap sequenceMap = new HashMap(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); results.put(label.getId(), Integer.valueOf(0)); sequenceMap.put(label.getSequence(), label.getId()); } iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); ItemTextIfc text = (ItemTextIfc) publishedItemTextHash.get(data.getPublishedItemTextId()); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); // if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) if (answer != null) { Integer num = (Integer) results.get(text.getId()); if (num == null) num = Integer.valueOf(0); ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) // only store correct responses in the results { results.put(text.getId(), Integer.valueOf(num.intValue() + 1)); } } } HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()]; int[] numarray = new int[results.keySet().size()]; ArrayList sequenceList = new ArrayList(); iter = labels.iterator(); while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); sequenceList.add(label.getSequence()); } Collections.sort(sequenceList); iter = sequenceList.iterator(); //iter = results.keySet().iterator(); int i = 0; int correctresponses = 0; while (iter.hasNext()) { Long sequenceId = (Long) iter.next(); Long textId = (Long) sequenceMap.get(sequenceId); ItemTextIfc text = (ItemTextIfc) texts.get(textId); int num = ((Integer) results.get(textId)).intValue(); numarray[i] = num; bars[i] = new HistogramBarBean(); bars[i].setLabel(text.getText()); bars[i].setNumStudents(num); if ((num>1)||(num==0)) { bars[i].setNumStudentsText(num + " " +rb.getString("correct_responses")); } else { bars[i].setNumStudentsText(num + " " +rc.getString("correct_response")); } i++; } // now calculate correctresponses // correctresponses = # of students who got all answers correct, for (Iterator it = numStudentRespondedMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); ArrayList resultsForOneStudent = (ArrayList) entry.getValue(); boolean hasIncorrect = false; Iterator listiter = resultsForOneStudent.iterator(); // numStudentRespondedMap only stores correct answers, so now we need to // check to see if # of rows in itemgradingdata_t == labels.size() // otherwise if a student only answered one correct answer and // skipped the rest, it would count as a correct response while (listiter.hasNext()) { ItemGradingData item = (ItemGradingData)listiter.next(); if (resultsForOneStudent.size()!= labels.size()){ hasIncorrect = true; break; } // now check each answer in Matching AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(item.getPublishedAnswerId()); if (answer.getIsCorrect() == null || (!answer.getIsCorrect().booleanValue())) { hasIncorrect = true; break; } } if (!hasIncorrect) { correctresponses = correctresponses + 1; qbean.addStudentWithAllCorrect(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } qbean.addStudentResponded(((ItemGradingData)resultsForOneStudent.get(0)).getAgentId()); } //NEW int[] heights = calColumnHeight(numarray, qbean.getNumResponses()); // int[] heights = calColumnHeight(numarray); for (i=0; i<bars.length; i++) { try { bars[i].setColumnHeight(Integer.toString(heights[i])); } catch (NullPointerException npe) { log.warn("bars[" + i + "] is null. " + npe); } } qbean.setHistogramBars(bars); if (qbean.getNumResponses() > 0) qbean.setPercentCorrect(Integer.toString((int)(((double) correctresponses/(double) qbean.getNumResponses()) * 100))); } private void getMatrixSurveyScores(HashMap publishedItemTextHash, HashMap publishedAnswerHash, List scores, HistogramQuestionScoresBean qbean, List labels) { HashMap texts = new HashMap(); HashMap rows = new HashMap(); HashMap answers = new HashMap(); HashMap numStudentRespondedMap = new HashMap(); Iterator iter = labels.iterator(); // create labels(rows) and HashMap , rows has the total count of response for that row while (iter.hasNext()) { ItemTextIfc label = (ItemTextIfc) iter.next(); texts.put(label.getId(), label); rows.put(label.getId(), Integer.valueOf(0)); // sequenceMap.put(label.getSequence(), label.getId()); } // log.info("kim debug: row size and texts size " + rows.keySet().size()+ " " + texts.keySet().size()); // result only contains the row information, I should have another HashMap to store the Answer results // find the number of responses (ItemGradingData) for each answer iter = scores.iterator(); while (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data .getPublishedAnswerId()); if (answer != null) { Integer num = null; // num is a counter try { // we found a response, now get existing count from the hashmap // num = (Integer) results.get(answer.getId()); num = (Integer) answers.get(answer.getId()); } catch (Exception e) { log.warn("No results for " + answer.getId()); log.error(e.getMessage()); } if (num == null) num = Integer.valueOf(0); answers.put(answer.getId(), Integer.valueOf(num.intValue() + 1)); Long id = ((ItemTextIfc)answer.getItemText()).getId(); Integer rCount = null; try { rCount = (Integer)rows.get(id); } catch (Exception e) { log.warn("No results for " + id); log.error(e.getMessage()); } if(rCount != null) rows.put(id, Integer.valueOf(rCount.intValue()+1)); } ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGradingId()); if (studentResponseList==null) { studentResponseList = new ArrayList(); } studentResponseList.add(data); numStudentRespondedMap.put(data.getAssessmentGradingId(), studentResponseList); qbean.addStudentResponded(data.getAgentId()); } //create the arraylist for answer text ArrayList answerTextList = new ArrayList<String>(); iter = publishedAnswerHash.keySet().iterator(); boolean isIn = false; while(iter.hasNext()){ Long id = (Long)iter.next(); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(id); if (!qbean.getItemId().equals(answer.getItem().getItemId())) { continue; } isIn = false; //log.info("kim debug: publishedAnswerHash: key value " + id + answer.getText()); for(int i=0; i< answerTextList.size(); i++){ if((((String)answer.getText()).trim()).equals(((String)answerTextList.get(i)).trim())){ isIn = true; break; } } if(!isIn){ String ansStr = answer.getText().trim(); answerTextList.add(ansStr); } } //create the HistogramBarBean ArrayList<HistogramBarBean> histogramBarList = new ArrayList<HistogramBarBean>(); iter = texts.keySet().iterator(); while (iter.hasNext()){ Long id = (Long)iter.next(); HistogramBarBean gramBar = new HistogramBarBean(); ItemTextIfc ifc = (ItemTextIfc)texts.get(id); Integer totalCount = (Integer)rows.get(id); //log.info("kim debug: total count: " + totalCount.intValue()); //log.info("kim debug: row.next()" + ifc.getText()); gramBar.setLabel(ifc.getText()); //add each small beans ArrayList<ItemBarBean> itemBars = new ArrayList<ItemBarBean>(); for(int i=0; i< answerTextList.size(); i++){ ItemBarBean barBean = new ItemBarBean(); int count = 0; //get the count of checked //1. first get the answerId for ItemText+AnswerText combination Iterator iter1 = publishedAnswerHash.keySet().iterator(); while(iter1.hasNext()){ Long id1 = (Long)iter1.next(); AnswerIfc answer1 = (AnswerIfc)publishedAnswerHash.get(id1); //log.info("kim debug:answer1.getText() + ifc.getText()" + //answer1.getText() + answer1.getItemText().getText() + ifc.getText() + answer1.getId()); // bjones86 - SAM-2232 - null checks if( answer1 == null ) { continue; } ItemTextIfc answer1ItemText = answer1.getItemText(); if( answer1ItemText == null ) { continue; } String answer1Text = answer1.getText(); String answer1ItemTextText = answer1ItemText.getText(); if( answer1Text == null || answer1ItemTextText == null ) { continue; } String answerText = (String) answerTextList.get( i ); String ifcText = ifc.getText(); if(answer1Text.equals(answerText) && answer1ItemTextText.equals(ifcText)) { //2. then get the count from HashMap if(answers.containsKey(answer1.getId())) { count =((Integer) answers.get(answer1.getId())).intValue(); //log.info("kim debug: count " + count); break; } } } if (count > 1) barBean.setNumStudentsText(count + " responses"); else barBean.setNumStudentsText(count + " response"); //2. get the answer text barBean.setItemText((String)answerTextList.get(i)); //log.info("kim debug: getItemText " + barBean.getItemText()); //3. set the columnHeight int height= 0; if (totalCount.intValue() != 0) height = 300 * count/totalCount.intValue(); barBean.setColumnHeight(Integer.toString(height)); itemBars.add(barBean); } //log.info("kim debug: itemBars size: " +itemBars.size()); gramBar.setItemBars(itemBars); histogramBarList.add(gramBar); } //debug purpose //log.info("kim debug: histogramBarList size: " +histogramBarList.size()); qbean.setHistogramBars(histogramBarList.toArray(new HistogramBarBean[histogramBarList.size()])); qbean.setNumResponses(numStudentRespondedMap.size()); } private void doScoreStatistics(HistogramQuestionScoresBean qbean, ArrayList scores) { // here scores contain ItemGradingData Map assessmentMap = getAssessmentStatisticsMap(scores); // test to see if it gets back empty map if (assessmentMap.isEmpty()) { qbean.setNumResponses(0); } try { BeanUtils.populate(qbean, assessmentMap); // quartiles don't seem to be working, workaround qbean.setQ1( (String) assessmentMap.get("q1")); qbean.setQ2( (String) assessmentMap.get("q2")); qbean.setQ3( (String) assessmentMap.get("q3")); qbean.setQ4( (String) assessmentMap.get("q4")); //qbean.setTotalScore( (String) assessmentMap.get("maxScore")); HistogramBarBean[] bars = new HistogramBarBean[qbean.getColumnHeight().length]; // SAK-1933: if there is no response, do not show bars at all // do not check if assessmentMap is empty, because it's never empty. if (scores.size() == 0) { bars = new HistogramBarBean[0]; } else { for (int i=0; i<qbean.getColumnHeight().length; i++) { bars[i] = new HistogramBarBean(); bars[i].setColumnHeight (Integer.toString(qbean.getColumnHeight()[i])); bars[i].setNumStudents(qbean.getNumStudentCollection()[i]); if (qbean.getNumStudentCollection()[i]>1) { bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Responses"); } else { bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + " Response"); } // bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] + // " Responses"); bars[i].setRangeInfo(qbean.getRangeCollection()[i]); bars[i].setLabel(qbean.getRangeCollection()[i]); } } qbean.setHistogramBars(bars); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } private Map getAssessmentStatisticsMap(ArrayList scoreList) { // this function is used to calculate stats for an entire assessment // or for a non-autograded question // depending on data's instanceof Iterator iter = scoreList.iterator(); ArrayList doubles = new ArrayList(); while (iter.hasNext()) { Object data = iter.next(); if (data instanceof AssessmentGradingData) { Double finalScore = ((AssessmentGradingData) data).getFinalScore(); if (finalScore == null) { finalScore = Double.valueOf("0"); } doubles.add(finalScore); } else { double autoScore = (double) 0.0; if (((ItemGradingData) data).getAutoScore() != null) autoScore = ((ItemGradingData) data).getAutoScore().doubleValue(); double overrideScore = (double) 0.0; if (((ItemGradingData) data).getOverrideScore() != null) overrideScore = ((ItemGradingData) data).getOverrideScore().doubleValue(); doubles.add(Double.valueOf(autoScore + overrideScore)); } } if (doubles.isEmpty()) doubles.add(new Double(0.0)); Object[] array = doubles.toArray(); Arrays.sort(array); double[] scores = new double[array.length]; for (int i=0; i<array.length; i++) { scores[i] = ((Double) array[i]).doubleValue(); } HashMap statMap = new HashMap(); double min = scores[0]; double max = scores[scores.length - 1]; double total = calTotal(scores); double mean = calMean(scores, total); int interval = 0; interval = calInterval(min, max); // SAM-2409 int[] numStudents = calNumStudents(scores, min, max, interval); statMap.put("maxScore", castingNum(max,2)); statMap.put("interval", Integer.valueOf(interval)); statMap.put("numResponses", Integer.valueOf(scoreList.size())); // statMap.put("numResponses", Integer.valueOf(scores.length)); statMap.put("totalScore",castingNum(total,2)); statMap.put("mean", castingNum(mean,2)); statMap.put("median", castingNum(calMedian(scores),2)); statMap.put("mode", castingNumForMode(calMode(scores))); statMap.put("numStudentCollection", numStudents); statMap.put( "rangeCollection", calRange(scores, numStudents, min, max, interval)); statMap.put("standDev", castingNum(calStandDev(scores, mean),2)); //NEW //statMap.put("columnHeight", calColumnHeight(numStudents)); statMap.put("columnHeight", calColumnHeight(numStudents,scoreList.size())); statMap.put("arrayLength", Integer.valueOf(numStudents.length)); statMap.put( "range", castingNum(scores[0],2) + " - " + castingNum(scores[scores.length - 1],2)); statMap.put("q1", castingNum(calQuartiles(scores, 0.25),2)); statMap.put("q2", castingNum(calQuartiles(scores, 0.5),2)); statMap.put("q3", castingNum(calQuartiles(scores, 0.75),2)); statMap.put("q4", castingNum(max,2)); return statMap; } /*** What follows is Huong Nguyen's statistics code. ***/ /*** We love you Huong! --rmg ***/ /** * Calculate the total score for all students * @param scores array of scores * @return the total */ private static double calTotal(double[] scores) { double total = 0; for(int i = 0; i < scores.length; i++) { total = total + scores[i]; } return total; } /** * Calculate mean. * * @param scores array of scores * @param total the total of all scores * * @return mean */ private static double calMean(double[] scores, double total) { return total / scores.length; } /** * Calculate median. * * @param scores array of scores * * @return median */ private static double calMedian(double[] scores) { double median; if(((scores.length) % 2) == 0) { median = (scores[(scores.length / 2)] + scores[(scores.length / 2) - 1]) / 2; } else { median = scores[(scores.length - 1) / 2]; } return median; } /** * Calculate mode * * @param scores array of scores * * @return mode */ private static String calMode(double[]scores){ // double[]scores={1,2,3,4,3,6,5,5,6}; Arrays.sort(scores); String maxString=""+scores[0]; int maxCount=1; int currentCount=1; for(int i=1;i<scores.length;i++){ if(!(""+scores[i]).equals(""+scores[i-1])){ currentCount=1; if(maxCount==currentCount) maxString=maxString+", "+scores[i]; } else{ currentCount++; if(maxCount==currentCount) maxString=maxString+", "+scores[i]; if(maxCount<currentCount){ maxString=""+scores[i]; maxCount=currentCount; } } } return maxString; } /** * Calculate standard Deviation * * @param scores array of scores * @param mean the mean * @param total the total * * @return the standard deviation */ private static double calStandDev(double[] scores, double mean) { double total = 0; for(int i = 0; i < scores.length; i++) { total = total + ((scores[i] - mean) * (scores[i] - mean)); } return Math.sqrt(total / (scores.length - 1)); } /** * Calculate the interval to use for histograms. * * @param scores array of scores * @param min the minimum score * @param max the maximum score * * @return the interval */ private static int calInterval(double min, double max) // SAM-2409 { int interval; if((max - min) < 10) { interval = 1; } else { interval = (int) Math.ceil((Math.ceil(max) - Math.floor(min)) / 10); // SAM-2409 } return interval; } /** * Calculate the number for each answer. * * @param answers array of answers * * * @return array of number giving each answer. */ /* private static int[] calNum(String[] answers, String[] choices, String type) { int[] num = new int[choices.length]; for(int i = 0; i < answers.length; i++) { for(int j = 0; j < choices.length; j++) { if(type.equals("Multiple Correct Answer")) { // TODO: using Tokenizer because split() doesn't seem to work. StringTokenizer st = new StringTokenizer(answers[i], "|"); while(st.hasMoreTokens()) { String nt = st.nextToken(); if((nt.trim()).equals(choices[j].trim())) { num[j] = num[j] + 1; } } } else { if(answers[i].equals(choices[j])) { num[j] = num[j] + 1; } } } } return num; } */ /** * Calculate the number correct answer * * @param answers array of answers * @param correct the correct answer * * @return the number correct */ /* private int calCorrect(String[] answers, String correct) { int cal = 0; for(int i = 0; i < answers.length; i++) { if(answers[i].equals(correct)) { cal++; } } return cal; } */ /** * Calculate the number of students per interval for histograms. * * @param scores array of scores * @param min the minimum score * @param max the maximum score * @param interval the interval * * @return number of students per interval */ private static int[] calNumStudents( double[] scores, double min, double max, int interval) { if(min > max) { //log.info("max(" + max + ") <min(" + min + ")"); max = min; } min = Math.floor(min); // SAM-2409 max = Math.ceil(max); // SAM-2409 int[] numStudents = new int[(int) Math.ceil((max - min) / interval)]; // this handles a case where there are no num students, treats as if // a single value of 0 if(numStudents.length == 0) { numStudents = new int[1]; numStudents[0] = 0; } for(int i = 0; i < scores.length; i++) { if(scores[i] <= (min + interval)) { numStudents[0]++; } else { for(int j = 1; j < (numStudents.length); j++) { if( ((scores[i] > (min + (j * interval))) && (scores[i] <= (min + ((j + 1) * interval))))) { numStudents[j]++; break; } } } } return numStudents; } /** * Get range text for each interval * * @param answers array of ansers * * * @return array of range text strings for each interval */ /* private static String[] calRange(String[] answers, String[] choices) { String[] range = new String[choices.length]; int current = 0; // gracefully handle a condition where there are no answers if(answers.length == 0) { for(int i = 0; i < range.length; i++) { range[i] = "unknown"; } return range; } choices[0] = answers[0]; for(int a = 1; a < answers.length; a++) { if(! (answers[a].equals(choices[current]))) { current++; choices[current] = answers[a]; } } return range; } */ /** * Calculate range strings for each interval. * * @param scores array of scores * @param numStudents number of students for each interval * @param min the minimium * @param max the maximum * @param interval the number of intervals * * @return array of range strings for each interval. */ private static String[] calRange( double[] scores, int[] numStudents, double min, double max, int interval) { String[] ranges = new String[numStudents.length]; if(Double.compare(max, min) == 0){ String num = castingNum(min,2); ranges[0] = num + " - " + num; } else { ranges[0] = (int) min + " - " + (int) (min + interval); int i = 1; while(i < ranges.length) { if((((i + 1) * interval) + min) < max) { ranges[i] = ">" + (int) ((i * interval) + min) + " - " + (int) (((i + 1) * interval) + min); } else { ranges[i] = ">" + (int) ((i * interval) + min) + " - " + castingNum(max,2); } i++; } } return ranges; } /** * Calculate the height of each histogram column. * * @param numStudents the number of students for each column * * @return array of column heights */ /* private static int[] calColumnHeightold(int[] numStudents) { int length = numStudents.length; int[] temp = new int[length]; int[] height = new int[length]; int i = 0; while(i < length) { temp[i] = numStudents[i]; i++; } Arrays.sort(temp); int num = 1; if((temp.length > 0) && (temp[temp.length - 1] > 0)) { num = (int) (300 / temp[temp.length - 1]); int j = 0; while(j < length) { height[j] = num * numStudents[j]; j++; } } return height; } */ private static int[] calColumnHeight(int[] numStudents, int totalResponse) { int[] height = new int[numStudents.length]; int index=0; while(index <numStudents.length){ if(totalResponse>0) height[index] = (int)((100*numStudents[index])/totalResponse); else height[index]=0; index++; } return height; } /** * Calculate quartiles. * * @param scores score array * @param r the quartile rank * * @return the quartile */ private static double calQuartiles(double[] scores, double r) { int k; double f; k = (int) (Math.floor((r * (scores.length - 1)) + 1)); f = (r * (scores.length - 1)) - Math.floor(r * (scores.length - 1)); // special handling if insufficient data to calculate if(k < 2) { return scores[0]; } return scores[k - 1] + (f * (scores[k] - scores[k - 1])); } /** * DOCUMENTATION PENDING * * @param n DOCUMENTATION PENDING * * @return DOCUMENTATION PENDING */ private static String castingNum(double number,int decimal) { int indexOfDec=0; String n; int index; if(Math.ceil(number) == Math.floor(number)) { return ("" + (int) number); } else { n=""+number; indexOfDec=n.indexOf("."); index=indexOfDec+decimal+1; //log.info("NUMBER : "+n); //log.info("NUMBER LENGTH : "+n.length()); if(n.length()>index) { return n.substring(0,index); } else{ return ""+number; } } } private String castingNumForMode(String oldmode) // only show 2 decimal points for Mode { String[] tokens = oldmode.split(","); String[] roundedtokens = new String[tokens.length]; StringBuilder newModebuf = new StringBuilder(); for (int j = 0; j < tokens.length; j++) { roundedtokens[j] = castingNum(new Double(tokens[j]).doubleValue(), 2); newModebuf.append(", " + roundedtokens[j]); } String newMode = newModebuf.toString(); newMode = newMode.substring(2, newMode.length()); return newMode; } private String getType(int typeId) { ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ResourceLoader rc = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.CommonMessages"); if (typeId == TypeIfc.MULTIPLE_CHOICE.intValue()) { return rc.getString("multiple_choice_sin"); } if (typeId == TypeIfc.MULTIPLE_CORRECT.intValue()) { return rc.getString("multipl_mc_ms"); } if (typeId == TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.intValue()) { return rc.getString("multipl_mc_ss"); } if (typeId == TypeIfc.MULTIPLE_CHOICE_SURVEY.intValue()) { return rb.getString("q_mult_surv"); } if (typeId == TypeIfc.TRUE_FALSE.intValue()) { return rb.getString("q_tf"); } if (typeId == TypeIfc.ESSAY_QUESTION.intValue()) { return rb.getString("q_short_ess"); } if (typeId == TypeIfc.FILE_UPLOAD.intValue()) { return rb.getString("q_fu"); } if (typeId == TypeIfc.AUDIO_RECORDING.intValue()) { return rb.getString("q_aud"); } if (typeId == TypeIfc.FILL_IN_BLANK.intValue()) { return rb.getString("q_fib"); } if (typeId == TypeIfc.MATCHING.intValue()) { return rb.getString("q_match"); } if (typeId == TypeIfc.FILL_IN_NUMERIC.intValue()) { return rb.getString("q_fin"); } if (typeId == TypeIfc.EXTENDED_MATCHING_ITEMS.intValue()) { return rb.getString("q_emi"); } if (typeId == TypeIfc.MATRIX_CHOICES_SURVEY.intValue()) { return rb.getString("q_matrix_choices_surv"); } return ""; } /** * Standard process action method. * @param ae ActionEvent * @throws AbortProcessingException */ public List getDetailedStatisticsSpreadsheetData(String publishedId) throws AbortProcessingException { log.debug("HistogramAggregate Statistics LISTENER."); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean( "totalScores"); HistogramScoresBean bean = (HistogramScoresBean) ContextUtil.lookupBean( "histogramScores"); totalBean.setPublishedId(publishedId); //String publishedId = totalBean.getPublishedId(); if (!histogramScores(bean, totalBean)) { throw new RuntimeException("failed to call histogramScores."); } ArrayList spreadsheetRows = new ArrayList(); List<HistogramQuestionScoresBean> detailedStatistics = bean.getDetailedStatistics(); spreadsheetRows.add(bean.getShowPartAndTotalScoreSpreadsheetColumns()); //spreadsheetRows.add(bean.getShowDiscriminationColumn()); boolean showDetailedStatisticsSheet; if (totalBean.getFirstItem().equals("")) { showDetailedStatisticsSheet = false; spreadsheetRows.add(showDetailedStatisticsSheet); return spreadsheetRows; } else { showDetailedStatisticsSheet = true; spreadsheetRows.add(showDetailedStatisticsSheet); } if (detailedStatistics==null || detailedStatistics.size()==0) { return spreadsheetRows; } ResourceLoader rb = new ResourceLoader( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); ArrayList<Object> headerList = new ArrayList<Object>(); headerList = new ArrayList<Object>(); headerList.add(ExportResponsesBean.HEADER_MARKER); headerList.add(rb.getString("question")); if(bean.getRandomType()){ headerList.add("N(" + bean.getNumResponses() + ")"); }else{ headerList.add("N"); } headerList.add(rb.getString("pct_correct_of")); if (bean.getShowDiscriminationColumn()) { headerList.add(rb.getString("pct_correct_of")); headerList.add(rb.getString("pct_correct_of")); headerList.add(rb.getString("discrim_abbrev")); } headerList.add(rb.getString("frequency")); spreadsheetRows.add(headerList); headerList = new ArrayList<Object>(); headerList.add(ExportResponsesBean.HEADER_MARKER); headerList.add(""); headerList.add(""); headerList.add(rb.getString("whole_group")); if (bean.getShowDiscriminationColumn()) { headerList.add(rb.getString("upper_pct")); headerList.add(rb.getString("lower_pct")); headerList.add(""); } // No Answer headerList.add(rb.getString("no_answer")); // Label the response options A, B, C, ... int aChar = 65; for (char colHeader=65; colHeader < 65+bean.getMaxNumberOfAnswers(); colHeader++) { headerList.add(String.valueOf(colHeader)); } spreadsheetRows.add(headerList); //VULA-1948: sort the detailedStatistics list by Question Label sortQuestionScoresByLabel(detailedStatistics); Iterator detailedStatsIter = detailedStatistics.iterator(); ArrayList statsLine = null; while (detailedStatsIter.hasNext()) { HistogramQuestionScoresBean questionBean = (HistogramQuestionScoresBean)detailedStatsIter.next(); statsLine = new ArrayList(); statsLine.add(questionBean.getQuestionLabel()); Double dVal; statsLine.add(questionBean.getNumResponses()); try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrect()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrect()); } if (bean.getShowDiscriminationColumn()) { try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrectFromUpperQuartileStudents()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrectFromUpperQuartileStudents()); } try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getPercentCorrectFromLowerQuartileStudents()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getPercentCorrectFromLowerQuartileStudents()); } try { if (questionBean.getShowPercentageCorrectAndDiscriminationFigures()) { dVal = Double.parseDouble(questionBean.getDiscrimination()); statsLine.add(dVal); } else { statsLine.add(" "); } } catch (NumberFormatException ex) { statsLine.add(questionBean.getDiscrimination()); } } dVal = Double.parseDouble("" + questionBean.getNumberOfStudentsWithZeroAnswers()); statsLine.add(dVal); for (int i=0; i<questionBean.getHistogramBars().length; i++) { try { if (questionBean.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString()) && !questionBean.getQuestionLabel().contains("-")) { statsLine.add(" "); } else { if (questionBean.getHistogramBars()[i].getIsCorrect()) { statsLine.add(ExportResponsesBean.FORMAT_BOLD); } dVal = Double.parseDouble("" + questionBean.getHistogramBars()[i].getNumStudents() ); statsLine.add(dVal); } } catch (NullPointerException npe) { log.warn("questionBean.getHistogramBars()[" + i + "] is null. " + npe); } } spreadsheetRows.add(statsLine); } return spreadsheetRows; } /** * This method sort the detailedStatistics List by Question Label value * * @param detailedStatistics */ private void sortQuestionScoresByLabel(List<HistogramQuestionScoresBean> detailedStatistics) { //VULA-1948: sort the detailedStatistics list by Question Label Collections.sort(detailedStatistics, new Comparator<HistogramQuestionScoresBean>() { @Override public int compare(HistogramQuestionScoresBean arg0, HistogramQuestionScoresBean arg1) { HistogramQuestionScoresBean bean1 = (HistogramQuestionScoresBean) arg0; HistogramQuestionScoresBean bean2 = (HistogramQuestionScoresBean) arg1; //first check the part number int compare = Integer.valueOf(bean1.getPartNumber()) - Integer.valueOf(bean2.getPartNumber()); if (compare != 0) { return compare; } //now check the question number int number1 = 0; int number2 = 0; //check if the question has a sub-question number, only test the question number now if(bean1.getQuestionNumber().indexOf("-") == -1){ number1 = Integer.valueOf(bean1.getQuestionNumber()); }else{ number1 = Integer.valueOf(bean1.getQuestionNumber().substring(0, bean1.getQuestionNumber().indexOf("-"))); } if(bean2.getQuestionNumber().indexOf("-") == -1){ number2 = Integer.valueOf(bean2.getQuestionNumber()); }else{ number2 = Integer.valueOf(bean2.getQuestionNumber().substring(0, bean2.getQuestionNumber().indexOf("-"))); } compare = number1 - number2; if(compare != 0){ return compare; } //Now check the sub-question number. At this stage it will be from the same question number1 = Integer.valueOf(bean1.getQuestionNumber().substring(bean1.getQuestionNumber().indexOf("-")+1)); number2 = Integer.valueOf(bean2.getQuestionNumber().substring(bean2.getQuestionNumber().indexOf("-")+1)); return number1 - number2; } }); } private List<AssessmentGradingData> filterGradingData(List<AssessmentGradingData> submissionsSortedForDiscrim, Long itemId) { List<AssessmentGradingData> submissionsForItemSortedForDiscrim = new ArrayList<AssessmentGradingData>(); for(AssessmentGradingData agd: submissionsSortedForDiscrim){ Set<ItemGradingData> itemGradings = agd.getItemGradingSet(); for(ItemGradingData igd: itemGradings){ if(igd.getPublishedItemId().equals(itemId)){ submissionsForItemSortedForDiscrim.add(agd); break; } } } return submissionsForItemSortedForDiscrim; } }
SAM-2880:Double precision sum trouble leads to wrong score intervals (#2533)
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java
SAM-2880:Double precision sum trouble leads to wrong score intervals (#2533)
<ide><path>amigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java <ide> double[] scores = new double[array.length]; <ide> for (int i=0; i<array.length; i++) <ide> { <del> scores[i] = ((Double) array[i]).doubleValue(); <add> scores[i] = Double.valueOf(castingNum((Double)array[i],2)).doubleValue(); <ide> } <ide> <ide> HashMap statMap = new HashMap();